重叠 SQL 与分组依据

Overlap SQL with group by

我对 SQL 中的重叠有疑问,我的数据库中有以下结构和数据:

Table A (Id = uniqueidentifier)
| Name |  StartDate  |    EndDate    | DaysToReceive |
------------------------------------------------------
|   A  |  2019-08-26 |   2020-04-13  | 232           |
|   A  |  2019-12-15 |   2020-04-11  | 119           |
|   A  |  2020-03-06 |   2020-03-31  | 26            |
|   B  |  2020-01-07 |   2020-01-31  | 25            |
|   B  |  2020-02-11 |   2020-02-29  | 19            |

我需要获取接收天数,但如果有重叠,我需要最短日期和最长日期之间的差异,否则我使用 DaysToReceive 求和列。

我试图让结果看起来像这样:

| Name | DaysToReceive |
------------------------
   A   |     232
   B   |     44

我已设法获得此查询,但仅适用于重叠天数。

select DATEDIFF(d, MIN(t1.dt),MAX(t1.enddt)) + 1 as DaysToReceive
from (
    select distinct cp1.dt, min(cp2.dt) enddt
    from ( select StartDate as dt, Id from TableA ) cp1, 
         ( select EndDate as dt from TableA ) cp2
    where cp2.dt > cp1.dt cp1.Id = cp2.Id
    group by cp1.dt
    ) t1, TableA t2
where t2.StartDate between t1.dt and t1.enddt
group by t1.dt, t1.enddt

提前致谢。 干杯

检查这个

Select [name], Case when [InRange] = 1 
   then Max(DateDiff(dd, MinStartdate, MaxEnddate) + 1)
   Else
       Sum(DateDiff(dd, Startdate, Enddate) + 1)
   End as [Days]

from
(
Select Distinct a.[name], StartDate, EndDate, MinStartdate, MaxEnddate,
    Case when StartDate > MinStartdate and EndDate < MaxEnddate or 
    (StartDate = MinStartdate and EndDate = MaxEnddate)  then
        1 Else 0  
        End as [InRange]
from
(
SELECT [name], 
   Min(StartDate) AS MinStartdate, Max(EndDate) AS MaxEnddate 
FROM A
Group By [Name]

) Q
inner join A a
on a.[name] = q.[name]
) QQ

这里是 fiddle