我有一个包含名称和日期的表。
看起来像这样:
我需要它看起来像这样:
有可能吗?我找不到方法。
答案 0 :(得分:0)
尝试结合使用滞后差和运行总和
WITH CTE1
AS
(
SELECT CASE WHEN DATEDIFF(DAY,LAG(TODATE) OVER (ORDER BY TODATE),FROMDATE) =1 THEN NULL ELSE ROW_NUMBER() OVER (ORDER BY FROMDATE) END AS COL1 --in case the last ToDate and current FromDate are consecutive, use a NULL mark
,*
FROM Table
)
,CTE2 AS
(
SELECT SUM(ISNULL(COL1,0)) OVER (ORDER BY FROMDATE) AS RUNNINGSUM ----sum up consecutive rows adding 0 in case of a NULL value
,* FROM CTE1
)
SELECT NAME,MIN(FROMDATE) AS FROMDATE,MAX(TODATE) AS TODATE FROM CTE2
GROUP BY RUNNINGSUM,NAME