sqlsnowflake-cloud-data-platform

Create a year column based on the week commencing on Saturdays


I need to create a new column YEAR_SAT_FRI.

There is a dimension table in Snowflake named DIM_DATE and we have columns DATE, YEAR. The requirement is to add a year column based on the week commencing on Saturdays. If taking this week as an example, I need 28-5 31st December to be shown under 2025 YEAR_SAT_FRI for the column.

I tried the below logic but it is excluding 28/12/2024.

SELECT DATE, CASE WHEN DATE>=DATEADD(DAY,-(DAYOFWEEK(LAST_DAY(DATE,'YEAR'))%6),LAST_DAY(DATE,'YEAR'))
THEN YEAR(DATE)+1
ELSE YEAR(DATE)
END AS YEAR_SAT_FRI
FROM REPORTING.DIM_DATE

This query is showing 2025 only for dates between 29/12/2024 and 31/12/2024 but not for 28/12/2024.


Solution

  • Calculate the day of the week for the last day of the year and get the correct number of days to subtract to get to the last Saturday of the year

    ((DAYOFWEEK(LAST_DAY(DATE, 'YEAR')) + 1) % 7)
    

    And then the calculated number of days are subtracted from the last day of the year to get the last Saturday of the year

    SELECT DATE,
        CASE 
            WHEN DATE >= DATEADD(DAY, -((DAYOFWEEK(LAST_DAY(DATE, 'YEAR')) + 1) % 7), LAST_DAY(DATE, 'YEAR'))
            THEN YEAR(DATE) + 1 
            ELSE YEAR(DATE) 
        END AS YEAR_SAT_FRI 
    FROM DIM_DATE;
    

    Below is the output with test data

    30-12-2023 is Saturday so it is marked as 2024.

    28-12-2024 is Saturday so it is marked as 2025.

    Hope my understanding is correct.

    Date YEAR_SAT_FRI
    2023-12-27 2023
    2023-12-28 2023
    2023-12-29 2023
    2023-12-30 2024
    2023-12-31 2024
    2024-12-24 2024
    2024-12-25 2024
    2024-12-26 2024
    2024-12-27 2024
    2024-12-28 2025
    2024-12-28 2025
    2024-12-29 2025
    2024-12-30 2025
    2024-12-31 2025
    2025-01-01 2025