在 Postgres 中将重复的 OVER 子句组合在一起

Group repeated OVER clauses together in Postgres

是否可以在 Postgres 中以某种方式将几个重复的 OVER 子句组合在一起?

具有 CASE ... END 场景的示例:

   case
        when hhk = lag(hhk) over (order by hhk, product, dt)
        and product = lag(product) over (order by hhk, product, dt)
        then dt - lag(dt) over (order by hhk, product, dt)
        else null
    end as delta

子句over (order by hhk, product, dt)重复了三次。我正在寻找一种以某种方式将它们组合在一起的方法,如下所示(当然不能这样工作):

    case
        -- here we combine the two conditions into one
        when [hhk, product] = lag([hhk, product]) 
            over (order by hhk, product, dt)
        -- and here we somehow recall the clause
        then dt - lag(dt) over (my_clause)
        else null
    end as delta

您可以在 FROM 子句中定义一个 window。例如:

select v.*, row_number() over w
from (values (1, 2), (1, 3)) v(x, y)
     window w as (partition by x order by y)

在你的具体例子中,我可以推测是这样的:

select . . .
       (case when household_key = lag(household_key) over w and
                  product_id = lag(product_id) over w
        then dt - lag(dt) over w
        end) as delta
from . . .
     window w as (order by household_key, product_id, dt)