Skip to content
Advertisement

SQL date scenario for getting previous month’s data to-date on the 1st of month, then drop last month

I’m trying to recreate an existing View in Snowflake (originally in SQL Server). I need to get last month’s data which is easy enough, but here’s the scenario:

  • On 3-1-21, it should retrieve 2-1-21 to 3-1-21, but then starting on 3-2-21, it should only show 3-1-21 to-date, as our month end reporting goes out on the 1st of the month, and it should include all of the previous month’s data, but then on the 2nd of the month, it should only show 3-1-21 to-date. Any idea how to do this? I can get last month’s data plus the first, but I don’t know how to make it drop the previous month and show MTD after the 2nd of the month.

     WHERE DATE(CHDCR, 'YYYYMMDD') >= ADD_MONTHS(CURRENT_DATE()-1,-1)
    

Advertisement

Answer

WITH dates AS (SELECT * FROM VALUES ('2021-03-01'),
     ('2021-03-02'),
     ('2021-03-03'),
     ('2021-02-01'),
     ('2021-02-02') v(day))
SELECT day
    ,DATE_TRUNC('month',DATEADD('day',-1, day)) AS from_date
    ,DATEADD('month',1, from_date ) AS to_date
FROM dates
ORDER BY 1;

we get the results:

DAY         FROM_DATE                   TO_DATE
2021-02-01  2021-01-01 00:00:00.000     2021-02-01 00:00:00.000
2021-02-02  2021-02-01 00:00:00.000     2021-03-01 00:00:00.000
2021-03-01  2021-02-01 00:00:00.000     2021-03-01 00:00:00.000
2021-03-02  2021-03-01 00:00:00.000     2021-04-01 00:00:00.000
2021-03-03  2021-03-01 00:00:00.000     2021-04-01 00:00:00.000
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement