t-sqlsnowflake-cloud-data-platform

Use Date table as a scaffold for dated information


Given a date table and a data table that contains identifies and a date:

Ident Date
A 1/05/2025
A 3/02/2025
A 4/15/2025

Get a result like:

Year Month Ident Date
2025 01 A 1/05/2025
2025 02
2025 03 A 3/02/2025
2025 04 A 4/15/2025
2025 05
2025 06
2025 07

Etc.

So, like how linking dated information to a Date dimension table in Power Bi will give you similar results where year/month with no data shows the year/month and blank.


Solution

  • As mentioned in comments, I am assuming there is limited set of data given in the question.
    You already mentioned there is a date dimension in PowerBI which can be used.In the query below I have created a temporary date dimension for the year 2025 for each month.This date dimension can be joined with your table on year and month.

    Sample query is in Snowflake since you mentioned it is going to be implemented in Snowflake.

    WITH date_range AS (
        SELECT DATEADD(MONTH, seq4(), '2025-01-01') AS month_start
        FROM TABLE(GENERATOR(ROWCOUNT => 12)) -- 2025 for 12 months
    )
    ,date_dim AS 
    (SELECT YEAR(month_start) AS Year,MONTH(month_start) AS Month
    FROM date_range
    )
    SELECT 
    d.Year,d.Month,t.Ident,t.Date
    FROM date_dim d
    LEFT JOIN  t
    ON d.Year = YEAR(t.Date)
    AND d.Month = MONTH(t.Date)
    ORDER BY d.Year, d.Month;
    

    Output

    enter image description here