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

时间:2019-03-04 12:45:26

标签: sql postgresql window-functions

是否可以在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

1 个答案:

答案 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)