使用模数时如何分组

How to group by when using a modulo

对于每家公司,我想 sum 最近 4 个季度的 收入 ,然后是 4 个后续季度,依此类推在(有关详细信息,请参见所附的屏幕截图)。我怎样才能做到这一点? SQL 查询和结果 - 第一次尝试(失败) https://i.stack.imgur.com/wWhhb.png

SELECT 
    ticker, 
    period_end_date, 
    revenue,
    1+ ((rn - 1) % 4) AS test
FROM (
    SELECT 
        ticker, 
        period_end_date,
        revenue,
        ROW_NUMBER() OVER (PARTITION BY ticker ORDER BY period_end_date DESC) rn
    FROM "ANALYTICS"."vQUARTERLY_MASTER_MATERIALIZED"
    --WHERE ticker = 'ACN'
    ORDER BY ticker
) q

编辑:以下代码满足我的需要。 'revenue' 使用最近一个季度和之后的 3 个季度求和。

SELECT 
    ticker, 
    period_end_date, 
    SUM(revenue) OVER (PARTITION BY ticker ORDER BY period_end_date DESC ROWS BETWEEN CURRENT ROW AND 3 FOLLOWING) AS total_revenue
    FROM "ANALYTICS"."vQUARTERLY_MASTER_MATERIALIZED"
--WHERE ticker = 'ACN'
ORDER BY ticker

你可以试试这个:

SELECT ticker 
     , period_end_date 
     , total_revenue
FROM (
    SELECT ticker 
         , period_end_date
         , SUM(revenue) OVER (PARTITION BY ticker ORDER BY period_end_date DESC ROWS BETWEEN CURRENT ROW AND 3 FOLLOWING) AS total_revenue
         , max(period_end_date) OVER (PARTITION BY ticker) AS period_end_date_max
    FROM "ANALYTICS"."vQUARTERLY_MASTER_MATERIALIZED"
    --WHERE ticker = 'ACN
     ) q
 WHERE EXTRACT(MONTH FROM period_end_date) = EXTRACT(MONTH FROM period_end_date_max)
 ORDER BY ticker, period_end_date ASC