SQL:按组划分的最大可能日期范围
Posted
技术标签:
【中文标题】SQL:按组划分的最大可能日期范围【英文标题】:SQL: Maximum possible date range by group 【发布时间】:2017-08-21 16:09:17 【问题描述】:我正在使用 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
有什么建议吗?
【问题讨论】:
你尝试了什么? 你想按照什么标准对它进行分组?因为你想要的结果是模棱两可的。 这是一个空白和孤岛问题。在这里查看blogs.msdn.microsoft.com/samlester/2012/09/04/… 【参考方案1】:将临时日历表用于间隙和孤岛解决方案:
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 |
+------------+------------+----+
【讨论】:
@Strawberry 抱歉,我在没有经过足够审查的情况下调整了引用的解决方案。我用这个代替了那个答案。以上是关于SQL:按组划分的最大可能日期范围的主要内容,如果未能解决你的问题,请参考以下文章