動態分組查詢

2021-04-16 17:49:14 字數 1750 閱讀 1078

--示例資料

create table 表(id int,num int)

insert 表 select 1,2

union all select 2,3

union all select 3,2

union all select 4,2

union all select 5,12

union all select 6,2

union all select 7,1

union all select 8,5

union all select 9,1

go/*--問題說明:

輸入分組引數,比如輸入 "3,6" ,實現按 id<=3,3

<=6,id>6 分組查詢

輸入分組引數,比如輸入 "2,5,8" ,實現按 id<=2,2

<=5,5

<=8,id>8 分組查詢

--*/

--查詢的儲存過程

create proc p_qry

@numlist varchar(1000)

asset nocount on

declare @t table(id int identity,組 varchar(10),a int,b int)

declare @i int,@pnum varchar(10)

select @i=charindex(',',@numlist+',')

,@pnum=left(@numlist,@i-1)

,@numlist=stuff(@numlist,1,@i,'')

,@i=charindex(',',@numlist)

insert @t select 'id<='+@pnum,null,@pnum

while @i>0

begin

insert @t select @pnum+'

<='+left(@numlist,@i-1),@pnum,left(@numlist,@i-1)

select @pnum=left(@numlist,@i-1)

,@numlist=stuff(@numlist,1,@i,'')

,@i=charindex(',',@numlist)

endinsert @t select 'id>'+@numlist,@numlist,null

select b.組,num=sum(a.num)

from 表 a,@t b

where case

when b.a is null then case when a.id<=b.b then 1 else 0 end

when b.b is null then case when a.id>b.a then 1 else 0 end

else case when a.id>b.a and a.id<=b.b then 1 else 0 end

end=1

group by b.組

order by min(b.id)

go--呼叫儲存過程進行查詢

exec p_qry '2,5,8'

go--刪除測試

drop table 表

drop proc p_qry

/*--測試結果

組          num        

---------- -----------

id<=2      52

<=5    16

id>8       1

--*/

動態分組查詢

示例資料 create table 表 id int,num int insert 表 select 1,2 union all select 2,3 union all select 3,2 union all select 4,2 union all select 5,12 union all ...

動態分組查詢

示例資料 create table 表 id int,num int insert 表 select 1,2 union all select 2,3 union all select 3,2 union all select 4,2 union all select 5,12 union all ...

動態分組查詢

示例資料 createtable表 idint,numint insert表select1,2 unionallselect2,3 unionallselect3,2 unionallselect4,2 unionallselect5,12 unionallselect6,2 unionallsel...