34,590
社区成员
发帖
与我相关
我的任务
分享
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')
go
select 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) text2
from prod
group by (id - 1)/2
/*
id1 text1 id2 text2
----------- ---------- ----------- ----------
1 a 2 b
3 c 4 d
5 e 6 f
(所影响的行数为 3 行)
*/
drop table prod
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')
go
select max(case when px % 2 = 1 then id else null end) id1,
max(case when px % 2 = 1 then [text] else null end) text1,
max(case when px % 2 = 0 then id else null end) id2,
max(case when px % 2 = 0 then [text] else null end) text2
from (select t.* , px = (select count(1) from prod where id < t.id) + 1 from prod t) m
group by (px - 1)/2
/*
id1 text1 id2 text2
----------- ---------- ----------- ----------
1 a 2 b
3 c 4 d
5 e 6 f
(所影响的行数为 3 行)
*/
drop table prod