简体   繁体   English

SQL 日期场景,用于在 1 日获取上个月的数据,然后在上个月下降

[英]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).我正在尝试在 Snowflake 中重新创建现有视图(最初在 SQL 服务器中)。 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.在 3-1-21,它应该检索 2-1-21 到 3-1-21,但是从 3-2-21 开始,它应该只显示 3-1-21 to-date,作为我们的月末报告每月 1 号出去,它应该包括上个月的所有数据,但是在每月 2 号,它应该只显示 3-1-21 到日期。 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.我可以得到上个月的数据加上第一个,但我不知道如何让它下降上个月并在每月 2 日之后显示 MTD。

     WHERE DATE(CHDCR, 'YYYYMMDD') >= ADD_MONTHS(CURRENT_DATE()-1,-1)
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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM