Possible recursive CTE query using date ranges

前端 未结 3 1186
一向
一向 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条回答
  • 2020-12-21 03:06
    DECLARE @date DATE = GETDATE()
    
    ;WITH MonthsCTE AS (
        SELECT 1 [Month], DATEADD(DAY, -DATEPART(DAY, @date)+1, @date) as 'MonthStart'
        UNION ALL
        SELECT [Month] + 1, DATEADD(MONTH, 1, MonthStart)
        FROM MonthsCTE 
        WHERE [Month] < 12 )
    
    SELECT * FROM MonthsCTE
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-21 03:26

    You can cross join your request with a recursive CTE, this is a good idea.

    WITH thirteenMonthBack(myDate, level) as
    (
       SELECT GETDATE() as myDate, 0 as level
       UNION ALL
       SELECT DATEADD(month, -1, myDate), level + 1
       FROM thirteenMonthBack
       WHERE level < 13
    )
    SELECT xxx
    FROM youQuery
       CROSS JOIN thirteenMonthBack
    
    0 讨论(0)
提交回复
热议问题