我试图获得每个组的最小和最大行数,结束日期与下一行开始日期匹配
输入日期:
ResultUid BeginDate EndDate
1 1999-12-31 00:00:00.000 2000-01-31 00:00:00.000
1 2000-01-31 00:00:00.000 2000-02-29 00:00:00.000
1 2000-02-29 00:00:00.000 2000-03-31 00:00:00.000
1 2000-03-31 00:00:00.000 2000-04-30 00:00:00.000
1 2007-03-31 00:00:00.000 2007-04-30 00:00:00.000
1 2007-04-30 00:00:00.000 2007-05-31 00:00:00.000
1 2007-05-31 00:00:00.000 2007-06-30 00:00:00.000
期望的结果:
ResultUid BeginDate EndDate
1 1999-12-31 00:00:00.000 2000-04-30 00:00:00.000
1 2007-03-31 00:00:00.000 2007-06-30 00:00:00.000
我试过了:
SELECT
ResultUid,
MIN(BeginDate) AS "min",
MAX(EndDate) AS "max",
lag
FROM (
SELECT
ResultUid,
BeginDate,
EndDate,
DATEDIFF(MONTH,lag(BeginDate) OVER (order by EndDate), EndDate) AS "lag"
FROM Results
GROUP BY
ResultUid,
BeginDate,
EndDate
) sub
GROUP BY
ResultUid,
lag
答案 0 :(得分:2)
您可以通过检查上一个结束日期来确定组的开始位置。然后,可以通过累积和来为相邻日期组分配组ID:
select resultuid, min(begindate) as begindate, max(enddate) as enddate
from (select r.*,
sum(case when prev_enddate = begindate then 0 else 1 end) over
(partition by resultuid order by begindate) as grp
from (select r.*,
lag(enddate) over (partition by resultuid order by begindate) as prev_enddate
from results r
) r
) r
group by resultuid, grp;