Create a Simple Calendar or Date Dimension On-the-fly

 I have a report where I want the user to pick from 3 options for the date range on the report:

  1. Latest business date; generally this would be yesterday
  2. Week-to-date
  3. Month-to-date
The SQL below was actually used in Snowflake. Change CURRENT_DATE to GETDATE() for SQL Server. The idea is to get the list of dates from the CTE that are relevant and join to any fact table based on the value of the CALENDAR_KEY column. I use a format of yyyymmdd for CALENDAR_KEY.


WITH CTE_DATES (DATE_FILTER, CALENDAR_KEY) 

AS

(

    -- BUSINESS_DATE

    SELECT

        'BUSINESS-DATE' AS DATE_FILTER

    ,   CALENDAR_KEY   

    FROM CALENDAR

    WHERE FULL_DATE = CURRENT_DATE - 1  


    UNION ALL


    -- CURRENT WEEK thru BUSINESS_DATE

    SELECT

        'WEEK-TO-DATE'

    ,   CALENDAR_KEY

    FROM CALENDAR

    WHERE DATE_PART(WEEK, FULL_DATE) = DATE_PART(WEEK, CURRENT_DATE - 1)

    AND YEAR(FULL_DATE) = DATE_PART(YEAR, CURRENT_DATE - 1) 

    AND FULL_DATE <= CURRENT_DATE - 1


    UNION ALL


    -- CURRENT MONTH thru BUSINESS DATE

    SELECT

        'MONTH-TO-DATE'

    ,   CALENDAR_KEY

    FROM CALENDAR

    WHERE FULL_DATE BETWEEN

        DATE_FROM_PARTS(

            DATE_PART(YEAR, CURRENT_DATE - 1)

        ,   DATE_PART(MONTH, CURRENT_DATE - 1)

        ,   1

        ) 

    AND CURRENT_DATE - 1

)



/*

SELECT *

FROM CTE_DATES

ORDER BY CALENDAR_KEY


SELECT

    DATE_FILTER

,   COUNT(*) AS NUMBER_OF_DAYS    

,   MIN(CALENDAR_KEY) AS MIN_CALENDAR_KEY

,   MAX(CALENDAR_KEY) AS MAX_CALENDAR_KEY

FROM CTE_DATES

GROUP BY DATE_FILTER

*/


Comments

Popular posts from this blog

Using sp_executesql with OPENQUERY

Executing Remote Queries Safely and Efficiently with sp_executesql