• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

动态分组查询_sqlserver

sqlserver 搞代码 7年前 (2018-06-16) 159次浏览 已收录 0个评论

原帖地址:
http://community.csdn.net/Expert/topic/3428/3428792.xml?temp=.6476251

–示例数据
create table 表(ID int,NUM int)

http://www.gaodaima.com/34954.html动态分组查询_sqlserver

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<ID<=6,ID>6 分组查询
输入分组参数,比如输入 “2,5,8” ,实现按 ID<=2,2<ID<=5,5<ID<=8,ID>8 分组查询
–*/

–查询的存储过程
create proc p_qry
@numlist varchar(1000)
as
set 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+'<id<=’+left(@numlist,@i-1),@pnum,left(@numlist,@i-1)
 select @pnum=left(@numlist,@i-1)
  ,@numlist=stuff(@numlist,1,@i,”)
  ,@i=charindex(‘,’,@numlist)
end
insert @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      5
2<id<=5    16
id>8       1
–*/

欢迎大家阅读《动态分组查询_sqlserver,跪求各位点评,若觉得好的话请收藏本文,by 搞代码


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:动态分组查询_sqlserver

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址