代码之家  ›  专栏  ›  技术社区  ›  Jivan

在后记中把从句重复组合在一起

  •  0
  • Jivan  · 技术社区  · 5 年前

    有没有可能把几个重复的 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 回复  |  直到 5 年前
        1
  •  1
  •   Gordon Linoff    5 年前

    您可以在 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)