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),a int,b 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.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.groupdata
order by min(b.id)
go
spgroupcol '2,5,8,10'
drop table TestData
sql存储过程的单步调试要在Vs2008中,服务器管理器中连接上数据库,找到存储过程右键单步调试。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器