0

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

时期
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()))

当我查询我的表时

DATEADD(QUARTER, -1, "Period")  AS "Period Q-1"

我有以下结果(似乎计算 M-3 而不是宿舍):

时期 期间 Q-1
2017-08-01 2017-05-01
2017-09-01 2017-06-01
2017-10-01 2017-07-01

要重现该问题:

WITH input AS (select $1 "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"

但是第二季度和第三季度仍然无法正常工作。

4

1 回答 1

1

注意

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

相当于

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

而以下为输入时间戳返回与该季度第一天的午夜相对应的时间戳(请参阅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

如果目标是返回前几个季度的上个月的第一天(例如,期间 = 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"
;
于 2021-03-29T15:02:41.540 回答