1
我試圖讓每組的最小值和最大值的行相匹配的下一行開始日期集團由以前的日期值
輸入一個日期結束日期:
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