如何将一张表查询出的奇偶列用不同的列名合并成一张表并且列名不变
现在又一张表prod:
id text
1 a
2 b
3 c
4 d
5 e
6 f
我用:
select prod.id as id1,prod.text as text1 from prod where prod.id%2 =1
select prod.id as id2,prod.text as text2 from prod where prod.id%2 =0
分别查询出奇偶列,问题是如何把这个查询合并成一张表,并且列名(也就是分别起的别名)不变?
也就是结果为:
id1 text1 id2 text2
1 a 2 b
3 c 4 d
5 e 6 f
哪位大侠知道啊?
[解决办法]
--如果你能确保你的ID按顺序+1.
create table prod(id int,[text] varchar(10))insert into prod values(1 ,'a')insert into prod values(2 ,'b')insert into prod values(3 ,'c')insert into prod values(4 ,'d')insert into prod values(5 ,'e')insert into prod values(6 ,'f')goselect max(case when id % 2 = 1 then id else null end) id1, max(case when id % 2 = 1 then [text] else null end) text1, max(case when id % 2 = 0 then id else null end) id2, max(case when id % 2 = 0 then [text] else null end) text2from prodgroup by (id - 1)/2/*id1 text1 id2 text2 ----------- ---------- ----------- ---------- 1 a 2 b3 c 4 d5 e 6 f(所影响的行数为 3 行)*/drop table prod