找到最重叠的日子?

时间:2012-04-01 10:57:27

标签: 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  

这是期望的结果分析:

enter image description here

左侧的2个常见日期为8/19/1(显示在2个范围内)

右侧的4个常见日期为18/119/1(显示在4个范围内... 4> 2因此它应该获胜。)

期望的结果:

18/1

19/1

它们两者看起来重叠最多。

修改

这是日期时间范围的脚本。

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'

3 个答案:

答案 0 :(得分:3)

我担心这不是你想要的,但也许它可以帮助你(我已经没时间了):

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

答案 1 :(得分:3)

此查询将显示包含大多数事件的各个日期。 CTE tableOfDates生成一个从min(startDate)到max(enddate)的日期表。查询的主要部分只计算包含这一天的间隔。如果您想查看完整列表,请注释 top 1 with ties 部分。 There is Sql Fiddle version of it

; with tableOfDates as (
   select min (startdate) aDate, max(enddate) enddate
     from tbl
   union all
    select aDate + 1, enddate
      from tableOfDates
     where enddate > aDate
)
select top 1 with ties tableOfDates.aDate, count (*)
from tableOfDates
   inner join tbl
      on tableOfDates.aDate >= tbl.startDate
     and tableOfDates.aDate <= tbl.enddate
group by tableOfDates.aDate
order by 2 desc
option (maxrecursion 0)

答案 2 :(得分:0)

很棒的问题。

我是通过

来做的
  • 将所有日期范围扩展为单个/垂直记录 将'20110101','20110107'变成
    '20110101'
    '20110102'
    '20110103'
    '20110104'
    '20110105'
    '20110106'
    '20110107'

  • 然后,按个别日期分组并返回最大数量