MSSQL求連續ID內數量合計-常見解決方案

本文介绍使用MSSQL实现连续ID内数值的汇总计算。通过三种不同的方法:临时表、子查询以及窗口函数,展示了如何有效地计算一组连续记录内的数值总和。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

--> Title  : MSSQL求連續ID內數量合計-常見解決方案

 

--> Author : wufeng4552

 

--> Date   : 2009-12-04

 

if object_id('tb') is not null drop table tb

 

go

 

create table tb(ID varchar(10),Num decimal(10,2)) 

 

insert tb

 

select '001',200.00 union all

 

select '002',200.00 union all

 

select '003',300.00 union all

 

select '007',500.00 union all

 

select '008',800.00 union all

 

select '009',200.00 union all

 

select '012',100.00 union all

 

select '013',100.00 union all

 

select '014',200.00 union all

 

select '017',100.00 union all

 

select '018',400.00 union all

 

select '019',300.00 

 

-->方法 1 臨時表

 

if object_id('tempdb..#t1')is not null 

 

drop table #t1

 

if object_id('tempdb..#t2')is not null 

 

drop table #t2

 

go

 

--取出起號

 

select cnt=identity(int,1,1),* into #t1 from tb t where not exists(select 1 from tb where id=t.id-1)order by t.id

 

--取出止號

 

select cnt=identity(int,1,1),* into #t2 from tb t where not exists(select 1 from tb where id=t.id+1)order by t.id

 

select n.[start]+'-'+n.[end]起止號,sum(num)合計

 

from tb m,

 

(select a.ID [start],b.ID [end] from #t1 a,#t2 b where a.cnt=b.cnt) n

 

where m.ID between n.[start] and n.[end]

 

group by n.[start]+'-'+n.[end]

 

/*

 

起止號                  合計

 

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

 

001-003               700.00

 

007-009               1500.00

 

012-014               400.00

 

017-019               800.00

 

 

 

(4 個資料列受到影響)

 

 

 

*/

 

--方法 2

 

select case when min(t.id)!=max(t.id) then min(t.id)+'-'+max(t.id)else min(t.id)end 起止號, 

 

       sum(num)合計

 

from(

 

select ID,

 

       cnt=cast(ID as int)-(select count(*)from tb n where m.ID>n.ID),

 

       num

 

from tb m

 

)t group by cnt

 

/*

 

起止號                  合計

 

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

 

001-003               700.00

 

007-009               1500.00

 

012-014               400.00

 

017-019               800.00

 

 

 

(4 個資料列受到影響)

 

 

 

*/

 

--方法3

 

select case when min(t.id)!=max(t.id) then min(t.id)+'-'+max(t.id)else min(t.id)end 起止號, 

 

       sum(num)合計

 

from(

 

select id,cnt=id-row_number()over(order by getdate()),num from tb

 

)t group by cnt

 

/*

 

起止號                  合計

 

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

 

001-003               700.00

 

007-009               1500.00

 

012-014               400.00

 

017-019               800.00

 

 

 

(4 個資料列受到影響)

 

 

 

*/

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值