Roy*_*mir 5 sql-server sql-server-2008
我试着写一个会发出的查询:
最多重叠的日期/秒.
格式是 d/m/yyyy
所以我在这里有日期范围:
dateStart ----- dateEnd
1/1---7/1
8/1--15/1
16/1------20/1
8/1--------------21/1
17/1---19/1
18/1--19/1
Run Code Online (Sandbox Code Playgroud)
这是理想的结果分析:

左边的2个常见日是8/1和9/1 (出现在2个范围内)
在右边的4个常见日是18/1和19/1(出现在4个范围...... 4> 2所以它应该赢.)
期望的结果:
18/1
19/1
Run Code Online (Sandbox Code Playgroud)
它们看起来最重叠.
这是日期时间范围的脚本.
DECLARE @t table( dt1 DATETIME , dt2 DATETIME)
INSERT INTO @t
SELECT '20110101','20110107'
UNION ALL
SELECT '20110108','20110115'
UNION ALL
SELECT '20110116','20110120'
UNION ALL
SELECT '20110108','20110121'
UNION ALL
SELECT '20110117','20110119'
UNION ALL
SELECT '20110118','20110119'
Run Code Online (Sandbox Code Playgroud)
恐怕这并不完全是您想要的,但也许它对您有帮助(我的时间不多了):
DECLARE @tbl table( startdate DATETIME , enddate DATETIME)
INSERT INTO @tbl
SELECT '20110101','20110107'
UNION ALL
SELECT '20110108','20110115'
UNION ALL
SELECT '20110116','20110120'
UNION ALL
SELECT '20110108','20110121'
UNION ALL
SELECT '20110117','20110119'
UNION ALL
SELECT '20110118','20110119'
;with overlapping_events as(
select startdate, enddate
, (select sum(inTimeSpan)
from (
select case when startdate<=events.startdate then 1 else 0 end
+ case when enddate <= events.startdate then -1 else 0 end as inTimeSpan
from @tbl
where startdate <= events.startdate
or enddate <= events.startdate) as previous
) as overlapping
from @tbl events
)
select oe.*
from overlapping_events oe
order by overlapping desc, startdate asc, enddate asc
startdate enddate overlapping
2011-01-18 00:00:00.000 2011-01-19 00:00:00.000 4
2011-01-17 00:00:00.000 2011-01-19 00:00:00.000 3
2011-01-08 00:00:00.000 2011-01-15 00:00:00.000 2
2011-01-08 00:00:00.000 2011-01-21 00:00:00.000 2
2011-01-16 00:00:00.000 2011-01-20 00:00:00.000 2
2011-01-01 00:00:00.000 2011-01-07 00:00:00.000 1
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
136 次 |
| 最近记录: |