Possible recursive CTE query using date ranges

前端 未结 3 1263
一向
一向 2020-12-21 02:39

Not sure how to even phrase the title on this one!

I have the following data:

IF OBJECT_ID (\'tempdb..#data\') IS NOT NULL DROP TABLE #data
CREATE TA         


        
3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-21 03:19

    You don't need a "real" recursive CTE here. You can use one for the month references though:

    ;WITH Months
    as
    (
        SELECT DATEADD(day, -DATEPART(day, GETDATE())+1, GETDATE()) as 'MonthStart'
        UNION ALL
        SELECT DATEADD(month, -1, MonthStart) as 'MonthStart'
        FROM Months
    )
    

    Then you can JOIN to SELECT TOP 13 * FROM Months in your above query.

    I'm not going to try to parse all your CASE statements, but essentially you can use a GROUP BY on the date and the MonthStart fields, like:

    GROUP BY Datepart(year, monthstart), Datepart(month, monthstart)

    and aggregate by month. It will probably be easiest to have all your options (active, lapsed, etc) as columns and calculate each with a SUM(CASE WHEN ... THEN 1 ELSE 0 END) as it will be easier with a GROUP BY.

提交回复
热议问题