是否可以合并按月底拆分的记录?

时间:2019-07-03 10:08:41

标签: sql-server sql-server-2008

我有一个包含名称和日期的表。

看起来像这样:

https://i.stack.imgur.com/xuWSD.png

我需要它看起来像这样:

https://i.stack.imgur.com/CXXYL.png

有可能吗?我找不到方法。

1 个答案:

答案 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