加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

按日期范围查询ID断号情况,并进行聚合求和

发布时间:2020-12-13 20:36:31 所属栏目:百科 来源:网络整理
导读:问: 有一个表如下: IDsaleDatePrice 12008-1-140 22008-1-150 32008-1-224 62008-1-210 72008-1-312 82008-1-320 .... 要写一个存储过程,统计一段时间内各连续ID的价格合计,得到以下结果: 比如2008-1-1到2008-1-3,得到的结果为: ID_RangeTotoal_Price 1-3114

问:

有一个表如下:
IDsaleDatePrice
12008-1-140
22008-1-150
32008-1-224
62008-1-210
72008-1-312
82008-1-320
....
要写一个存储过程,统计一段时间内各连续ID的价格合计,得到以下结果:
比如2008-1-1到2008-1-3,得到的结果为:
ID_RangeTotoal_Price
1-3114
6-742
如果统计的是2008-1-1到2008-1-2,得到的结果是
ID_RangeTotoal_Price
1-3114
610
请问如何写这个存储过程?

答:

if object_id ( ' tempdb..#T ' ) is not null
drop table #T

create table #T(ID int ,SaleDate datetime ,Price int )
insert into #T select 1 , ' 2008-1-1 ' , 40
insert into #T select 2 , 50
insert into #T select 3 , ' 2008-1-2 ' , 24
insert into #T select 6 , 10
insert into #T select 7 , ' 2008-1-3 ' , 12
insert into #T select 8 , 20
go

create proc p_test
(
@begin_date datetime ,
@end_date datetime
)
as
select ID = ltrim (ID) +
case when exists ( select 1 from #T
where SaleDate between @begin_date and @end_date
and ID = a.ID + 1 ) then ' - ' +
ltrim (( select min (ID) from #Tb
where SaleDate between @begin_date and @end_date and ID >= a.ID
and not exists ( select 1 from #T
where SaleDate between @begin_date and @end_date
and ID = b.ID + 1 )
))
else '' end ,

Total_Price
= ( select sum (Price) from #Tb
where SaleDate between @begin_date and @end_date
and ID between a.ID and
(
select min (ID) from #Tb
where SaleDate between @begin_date and @end_date and ID >= a.ID
and not exists ( select 1 from #T
where SaleDate between @begin_date and @end_date
and ID = b.ID + 1 )
)
)

from #Ta
where SaleDate between @begin_date and @end_date
and not exists
(
select 1 from #T where ID = a.ID - 1 and SaleDate between @begin_date and @end_date )


go
exec p_test ' 2008-01-01 ' , ' 2008-01-03 '
exec p_test ' 2008-01-01 ' , ' 2008-01-02 '
go
drop table #T
drop proc p_test

/*
IDTotal_Price
------------------------------------
1-3114
6-842

(所影响的行数为2行)

IDTotal_Price
------------------------------------
1-3114
610

(所影响的行数为2行)
*/

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读