是否可以在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
答案 0 :(得分:1)
您可以在FROM
子句中定义一个窗口。例如:
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)