有意思的SQL问题
现在有一列值为
1
2
9
三个数
求每个数加1~3后的数
结果为 1 加1~3后为 1,2,3,4
2 加1~3后为 2,3,4,5
9 加1~3后为 9,10,11,12
合并相同值为
1
2
3
4
5
9
10
11
12
怎么求呀
[解决办法]
union 就行吧
select a+1 as a from 表
union
select a+2 as a from 表
union
select a+3 as a from 表
[解决办法]
declare @t table(idx int)
insert into @t
select 1 union
select 2 union
select 9
select idx from @t
union
select idx+id as idx from @t a
cross apply(
select 1 id
union
select 2
union
select 3
) b
[解决办法]
declare @a table(a int)
insert into @a
select 1 union all
select 2 union all
select 9
select * from @a union
select a+1 from @a union
select a+2 from @a union
select a+3 from @a
/*
a
1
2
3
4
5
9
10
11
12
*/
/*这只是思路,如果不只是加1~3的话,可以考虑用while*/
[解决办法]
3楼的集合运算,看起来最舒服呢。只是这里为什么用APPLY呢?
同时存在一个去除重复值的问题(叉积运算后的集合没有去重)。
稍微修改了下:
SELECT DISTINCT
idx
FROM ( SELECT idx + id AS idx
FROM @t a
CROSS JOIN ( VALUES ( 0), ( 1), ( 2), ( 3) ) AS t ( id )
) AS temp;
[解决办法]
CREATE TABLE A( T1 INT)
INSERT INTO A VALUES (1),(2),(9);
CREATE TABLE #T(T2 INT)
INSERT INTO #T VALUES (1),(2),(3);
SELECT T1 FROM A
UNION
SELECT T1+T2 FROM A,#T