博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
一个根据列的范围分组汇总的Sql存储过程
阅读量:7021 次
发布时间:2019-06-28

本文共 1790 字,大约阅读时间需要 5 分钟。

1.需求说明

有如下表数据:

ID          NUM

----------- -----------
1           2
2           3
3           2
4           2
5           12
6           2
7           1
8           5
9           1
10          1
11          1

输入分组参数,比如输入 "2,5,8,10" ,实现按 ID<=2,2<ID<=5,5<ID<=8,8<ID<=10,ID>10 分组查询,要得到下面的数据:

groupdata  num

---------- -----------
id<=2      5
2<id<=5    16
5<id<=8    8
8<id<=10   2
id>10      1

2.存储过程如下:

--测试数据

create table TestData(ID int,NUM int)

insert TestData 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

union all select 10,1

union all select 11,1

go

 

create proc spgroupcol

@numlist varchar(1000)

as

set nocount on

declare @t table(id int identity,groupdata varchar(10),int,int)

declare @i int,@pnum varchar(10),@j int

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

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

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

 

while @i>=1

begin

 select @numlist=substring(@numlist,@i+1,len(@numlist)-@i)

 select @j=charindex(',',@numlist) ;  

if @i=@j

    begin

    insert @t select @pnum+'<id<='+substring(@numlist,0,@i),@pnum,substring(@numlist,0,@i)

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

    end

else

    begin

    insert @t select @pnum+'<id<='+substring(@numlist,0,@i+1),@pnum,substring(@numlist,0,@i+1)

    select @pnum=left(@numlist,@i);

    end

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

end

 

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

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

from TestData a,@t b

where case 

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

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

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

 end=1

group by b.groupdata

order by min(b.id)

go

 

spgroupcol '2,5,8,10'

drop table TestData

sql存储过程的单步调试要在Vs2008中,服务器管理器中连接上数据库,找到存储过程右键单步调试。

本文转自生鱼片博客园博客,原文链接:http://www.cnblogs.com/carysun/archive/2009/09/12/groupcolumnscope.html,如需转载请自行联系原作者

你可能感兴趣的文章
objective-c基础教程——学习小结
查看>>
linux解压命令
查看>>
关于dd/bs和swap/swappiness
查看>>
【推荐】The Function Pointer Tutorials
查看>>
51CTO博客开通了!
查看>>
Google Reader或死于高昂的隐私诉讼案
查看>>
缓冲区溢出(二)
查看>>
js高级程序设计笔记(13章)
查看>>
Nginx安装PHP-FPM及优化
查看>>
Zabbix 3.2 监控部署
查看>>
seekBar,RatingBar拖动条
查看>>
JavaScript原型、原型链和继承
查看>>
git错误集
查看>>
谷歌深度学习公开课任务 1: notMNIST
查看>>
java锁的理解
查看>>
本地连接已连接上,但电脑无法上网
查看>>
WinAPI: PolyPolygon - 绘制一组多边形
查看>>
MusicXML 3.0 (16) - 小音符
查看>>
我的友情链接
查看>>
局域网中彻底隐身
查看>>