動態分組查詢

2021-04-17 03:28:52 字數 1439 閱讀 6459

--示例資料

createtable表(idint,numint)

insert表select1,2

unionallselect2,3

unionallselect3,2

unionallselect4,2

unionallselect5,12

unionallselect6,2

unionallselect7,1

unionallselect8,5

unionallselect9,1

go/*--問題說明:

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

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

--*/

--查詢的儲存過程

createprocp_qry

@numlistvarchar(1000)

assetnocounton

declare@ttable(idintidentity,組varchar(10),aint,bint)

declare@iint,@pnumvarchar(10)

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

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

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

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

insert@tselect'id<='+@pnum,null,@pnum

while@i>0

begin

insert@tselect@pnum+''+@numlist,@numlist,null

selectb.組,num=sum(a.num)

from表a,@tb

wherecase

whenb.aisnullthencasewhena.id<=b.bthen1else0end

whenb.bisnullthencasewhena.id>b.athen1else0end

elsecasewhena.id>b.aanda.id<=b.bthen1else0end

end=1

groupbyb.組

orderbymin(b.id)

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

execp_qry'2,5,8'

go--刪除測試

droptable表

dropprocp_qry

/*--測試結果

組         num        

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

id<=2     5

28      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 ...

動態分組查詢

示例資料 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 ...