SQL - combine consecutive date rows based on column

血红的双手。 提交于 2019-12-05 21:27:49

You can use a recursive CTE starting with the first row:

;WITH CTE AS (
        SELECT  TOP 1 *, 1 AS Id
        FROM    #t
        ORDER BY BegDate
        UNION ALL
        SELECT  t.*, c.Id + CASE WHEN t.quanitty = c.quanitty THEN 0 ELSE 1 END 
        FROM    CTE c
                JOIN #t t ON c.BegDate = DATEADD(MONTH, -1, t.BegDate)
    )
    SELECT  MIN(BegDate) AS BegDate, MAX(EndDate) AS EndDate, MIN(quanitty) AS quanitty
    FROM    CTE
    GROUP BY Id
    ORDER BY Id;

I loaded the sample data like so:

SELECT  CAST(t.BegDate AS DATE) AS BegDate
        , CAST(t.EndDate AS DATE) AS EndDate
        , CAST(t.quanitty AS INT) AS quanitty
INTO    #t
FROM    (   VALUES 
            ('1/1/2014','1/31/2014',1),
            ('2/1/2014','2/28/2014',1),
            ('3/1/2014','3/31/2014',2),
            ('4/1/2014','4/30/2014',4),
            ('5/1/2014','5/31/2014',4),
            ('6/1/2014','6/30/2014',4),
            ('7/1/2014','7/31/2014',2),
            ('8/1/2014','8/30/2014',2)
        ) AS t(BegDate,EndDate,quanitty);

check this

select  min(BegDate) as BegDate, max(EndDate) as EndDate, min(quanitty) as quanitty
from
(
    select *, row_number() over(partition by quanitty order by quanitty)  p_rno
    ,row_number() over(order by BegDate)  rno 
    --,row_number() over(partition by quanitty order by quanitty)-
    -- row_number() over(order by BegDate)  rno 
    from #t
) t
group by (p_rno-rno)
order by BegDate
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!