SQL:按组分组的最大可能日期范围

时间:2017-08-21 16:09:18

标签: sql-server tsql date

我正在使用T-SQL(Microsoft SQL Server Management Studio 2017),我有一个类似于以下内容的数据集:

BEGINDATE   ENDDATE     ID
2015-07-01  2015-07-12  1
2015-07-01  2015-07-12  1
2015-07-11  2015-07-15  1
2015-07-18  2015-08-04  1
2015-06-28  2015-07-04  2
2015-06-28  2015-07-03  2
2015-06-29  2015-07-04  2
2015-07-03  2015-07-15  2
2015-07-17  2015-07-20  2

我想要做的是按ID合并重叠日期(有一些例子可以做到这一点,但不是按组 - like this one)。

理想情况下,最终结果如下:

BEGINDATE   ENDDATE     ID
2015-07-01  2015-07-15  1
2015-07-18  2015-08-04  1
2015-06-28  2015-07-15  2
2015-07-17  2015-07-20  2

有什么建议吗?

1 个答案:

答案 0 :(得分:1)

使用adhoc日历表获取gap-and-islands解决方案:

declare @fromdate date, @thrudate date;
select  @fromdate = min(begindate), @thrudate = max(enddate) from t;
;with n as (select n from (values(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) t(n))
, dates as (
  select top (datediff(day, @fromdate, @thrudate)+1) 
      [Date]=convert(date,dateadd(day,row_number() over(order by (select 1))-1,@fromdate))
  from n as deka cross join n as hecto cross join n as kilo
                 cross join n as tenK cross join n as hundredK
   order by [Date]
)
, cte as (
select
    t.id
  , d.date
  , grp = row_number() over (partition by t.id order by d.date)
        - datediff(day,@fromdate,d.date)
from dates d
  inner join t
    on d.date >= t.begindate
   and d.date <= t.enddate
group by t.id, d.date
)
select 
    BeginDate = min(cte.date)
  , EndDate   = max(cte.date)
  , id
from cte
where id is not null
group by id, grp
order by id, BeginDate

rextester演示:http://rextester.com/NKGY7104

返回:

+------------+------------+----+
| BeginDate  |  EndDate   | id |
+------------+------------+----+
| 2015-07-01 | 2015-07-15 |  1 |
| 2015-07-18 | 2015-08-04 |  1 |
| 2015-06-28 | 2015-07-15 |  2 |
| 2015-07-17 | 2015-07-20 |  2 |
+------------+------------+----+