22,209
社区成员
发帖
与我相关
我的任务
分享
--如果ID不是连续的。
--> 测试数据: [tb]
if object_id('[tb]') is not null drop table [tb]
create table [tb] (id int)
insert into [tb]
select 1 union all
select 5 union all
select 2 union all
select 8 union all
select 9 union all
select 23 union all
select 54 union all
select 7 union all
select 12 union all
select 34
select px=identity(int,1,1),* into # from tb
select id1=max(case px%3 when 1 then id else 0 end),
id2=max(case px%3 when 2 then id else 0 end),
id3=max(case px%3 when 0 then id else 0 end)
from #
group by case px%3 when 0 then px/3-1 else px/3 end
--结果:
id1 id2 id3
----------- ----------- -----------
1 5 2
8 9 23
54 7 12
34 0 0
select sum(case when (number-1)%3=0 then number else 0 end) id1,
sum(case when (number-1)%3=1 then number else 0 end) id2,
sum(case when (number-1)%3=2 then number else 0 end) id3
from (select number,grp=(number-1)/3
from master.dbo.spt_values where type='p' and number>=1) t
group by grp
/*
1 2 3
4 5 6
7 8 9
10 11 12
13 14 15
16 17 18
。。。
*/
--> 测试数据: [tb]
if object_id('[tb]') is not null drop table [tb]
create table [tb] (id int)
insert into [tb]
select 1 union all
select 2 union all
select 3 union all
select 4 union all
select 5 union all
select 6 union all
select 7 union all
select 8 union all
select 9 union all
select 10
select id1=max(case xh when 1 then id else 0 end),
id2=max(case xh when 2 then id else 0 end),
id3=max(case xh when 3 then id else 0 end)
from
(select px=case id%3 when 0 then id/3-1 else id/3 end,xh=case id%3 when 0 then 3 else id%3 end,* from [tb])a
group by px
--结果:
id1 id2 id3
----------- ----------- -----------
1 2 3
4 5 6
7 8 9
10 0 0
create table s(a int)
insert into s select 1 union select 2 union select 3 union select 4 union select 5 union select 6
union select 7 union select 8 union select 9 union select 10 union select 11
select * from s
select
max(case when (a-1)%3=0 then a else 0 end) a,
max(case when (a-1)%3=1 then a else 0 end) b,
max(case when (a-1)%3=2 then a else 0 end) c
from s
group by (a-1)/3
a b c
----------- ----------- -----------
1 2 3
4 5 6
7 8 9
10 11 0
(所影响的行数为 4 行)