码迷,mamicode.com
首页 > 数据库 > 详细

SQL经典问题 找出连续日期及连续的天数

时间:2017-11-17 14:54:40      阅读:181      评论:0      收藏:0      [点我收藏+]

标签:影响   除了   top   空值   tool   img   class   group by   sel   

转自:http://bbs.csdn.net/topics/360019248

如何取到每段连续日期的起始终止日期以及持续天数及起始日期距上一期终止日期的天数,能否用一句sql实现?
备注:数据库环境是sql server 2000

技术分享
create table tmptable(rq datetime)
go
insert tmptable values(‘2010.1.1‘)
insert tmptable values(‘2010.1.2‘)
insert tmptable values(‘2010.1.3‘)
insert tmptable values(‘2010.1.6‘)
insert tmptable values(‘2010.1.7‘)
insert tmptable values(‘2010.1.10‘)
insert tmptable values(‘2010.1.11‘)
insert tmptable values(‘2010.1.12‘)
insert tmptable values(‘2010.1.19‘)
insert tmptable values(‘2010.1.20‘)
insert tmptable values(‘2010.1.22‘)
insert tmptable values(‘2010.1.23‘)
insert tmptable values(‘2010.1.28‘)
go
---希望得到的结果
--本期起始日期 本期终止日期  持续天数 距上一期天数
--2010.1.1     2010.1.3      3        0
--2010.1.6     2010.1.7      2        3
--2010.1.10    2010.1.12     3        3
--2010.1.19    2010.1.20     2        7
--2010.1.22    2010.1.23     2        2
--2010.1.28    2010.1.28     1        5

drop table tmptable
go
技术分享

一句sql实现

技术分享
select 本期起始日期=min(rq),本期终止日期=max(rq),持续天数=max(id1)-min(id1)+1,
    距上一期天数=case a.id1-a.id2 when -1 then 0 else max(datediff(d,rq2,rq)) end 
from (
    select id1=datediff(d,‘2010-01-01‘,rq),id2=(select count(1) from tmptable where rq <= a.rq),rq2=(select max(rq) from tmptable where rq < a.rq),* from tmptable a
) a
group by a.id1-a.id2
/*
本期起始日期                  本期终止日期                  持续天数        距上一期天数
----------------------- ----------------------- ----------- -----------
2010-01-01 00:00:00.000 2010-01-03 00:00:00.000 3           0
2010-01-06 00:00:00.000 2010-01-07 00:00:00.000 2           3
2010-01-10 00:00:00.000 2010-01-12 00:00:00.000 3           3
2010-01-19 00:00:00.000 2010-01-20 00:00:00.000 2           7
2010-01-22 00:00:00.000 2010-01-23 00:00:00.000 2           2
2010-01-28 00:00:00.000 2010-01-28 00:00:00.000 1           5
警告: 聚合或其他 SET 操作消除了空值。
 
(6 行受影响)
*/
技术分享

SQL经典问题 找出连续日期及连续的天数

标签:影响   除了   top   空值   tool   img   class   group by   sel   

原文地址:http://www.cnblogs.com/wewedounai/p/7851058.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!