sqldatecalendarsnowflake-cloud-data-platformdatediff

Working days between two dates in Snowflake


Is there any ways to calculate working days between two dates in snowflake without creating calendar table, only using "datediff" function


Solution

  • After doing research work on snowflake datediff function, I have found the following conclusions.

    1. DATEDIFF(DAY/WEEK, START_DATE, END_DATE) will calculate difference, but the last date will be considered as END_DATE -1.
    2. DATEDIFF(WEEK, START_DATE, END_DATE) will count number of Sundays between two dates.

    By summarizing these two points, I have implemented the logic below.

    SELECT 
        ( DATEDIFF(DAY, START_DATE, DATEADD(DAY, 1, END_DATE))
        - DATEDIFF(WEEK, START_DATE, DATEADD(DAY, 1, END_DATE))*2 
        - (CASE WHEN DAYNAME(START_DATE) != 'Sun' THEN 1 ELSE 0 END)
        + (CASE WHEN DAYNAME(END_DATE) != 'Sat' THEN 1 ELSE 0 END)
        ) AS WORKING_DAYS