自定义期间滚动季度的雪花怪异日期问题

snwoflake weird date issue with rolling quarters on custom period

我无法使用自定义周期计算滚动季度 table:

Period
2017-06-01
2020-12-01
2020-11-01

滚动月份和年份有效:

  DATEADD(MONTH, -2, "Period") AS "Period M-2"
  DATEADD(YEAR, -1, "Period") AS "Period Y-1"

当我使用current_date()查询宿舍时,这是工作 :

SELECT DATE_TRUNC('MONTH',DATEADD(QUARTER, -1, current_date()))

当我用

查询我的table
DATEADD(QUARTER, -1, "Period")  AS "Period Q-1"

我有以下结果(似乎计算的是 M-3 而不是四分之一):

Period Period Q-1
2017-08-01 2017-05-01
2017-09-01 2017-06-01
2017-10-01 2017-07-01

要重现问题:

WITH input AS (select  "Period" from values 
('2017-08-01'),
('2017-09-01'),
('2017-10-01'),
('2017-05-01'),
('2020-11-01'),
('2020-11-01'),
('2017-04-01'),
('2020-10-01'),
('2020-10-01')
)
SELECT "Period",
DATE(DATEADD(MONTH, -1, "Period" )) AS  "Period M-1",
DATE(DATEADD(MONTH, -2, "Period" )) AS  "Period M-2",
DATE(DATEADD(QUARTER, -1, "Period" )) AS  "Period Q-1",
DATE(DATEADD(QUARTER, -2, "Period" )) AS  "Period Q-2",
DATE(DATEADD(YEAR, -1, "Period" )) AS  "Period Y-1",
DATE(DATEADD(YEAR, -2, "Period" )) AS  "Period Y-2"
FROM input

更新: 这是使用这个公式,谢谢你的解释@Francesco。

  DATE_TRUNC('MONTH',DATEADD('DAY', -1, DATE_TRUNC('QUARTER', "Period"))) AS "Period Q1"

但是Q2&Q3还是不行。

注意

DATEADD(QUARTER, -<value>, <date> )

相当于

DATEADD(MONTH, -<value>, <date> )

而下面的 returns 对应于输入时间戳的季度第一天午夜的时间戳(参见 https://docs.snowflake.com/en/sql-reference/functions/date_trunc.html

DATE_TRUNC('QUARTER', <date> )

因此,作为例子,下面

SELECT DATE_TRUNC('QUARTER', DATEADD(QUARTER, -1, '2021-03-29'));

正在返回 2020-10-01 00:00:00.000

如果目标是 return 前几个季度的上个月的第一天(例如,期间 =2020-04-01 即 Q-1 = 2020-03-01,Q- 2 = 2019-12-01, Q-3= 2019-09-01):

SELECT 
    DATEADD(MONTH, -1, DATEADD(QUARTER, 1
                                , DATE_TRUNC('QUARTER', DATEADD(QUARTER, -1, <date>))
                                )
                   ) AS "Q-1",
    DATEADD(MONTH, -1, DATEADD(QUARTER, 1
                                , DATE_TRUNC('QUARTER', DATEADD(QUARTER, -2, <date>))
                                )
                   ) AS "Q-2",
    DATEADD(MONTH, -1, DATEADD(QUARTER, 1
                                , DATE_TRUNC('QUARTER', DATEADD(QUARTER, -3, <date>))
                                )
                   ) AS "Q-3"
;