【问题标题】:SQL Snowflake FILTER function - update row conditionallySQL Snowflake FILTER 函数 - 有条件地更新行
【发布时间】:2021-09-12 23:36:39
【问题描述】:

我正在尝试编写一个查询,在该查询中我根据其他条件更新计数器。例如:

with table1 as (select *, count from table1)

select box_type, 
case when box_type = lag(box_type) over (order by time) 
then 
  count, update table1 set count = count + 1
else
  count
end as identifier

这是我正在尝试做的基本要点。我想要一个如下所示的表格:

box_type    identifier
small        1
small        1
small        1
medium       2
medium       2
large        3
large        3
small        4

我最初需要在 Postgresql 中执行此操作。解决办法是

select t1.*,
       count(*) filter (where box_type is distinct from prev_box_type) over (order by time) as count
from (select t1.*,
             lag(box_type) over (order by time) as prev_box_type
      from table1 t1
     ) t1

但我无法让它在 Snowflake 语法中工作。

谢谢!

【问题讨论】:

    标签: sql postgresql snowflake-cloud-data-platform snowflake-schema


    【解决方案1】:

    一种方法是:

    select t1.*,
           sum(case when box_type is distinct from prev_box_type then 1 else 0 end) over (order by time) as count
    from (select t1.*,
                 lag(box_type) over (order by time) as prev_box_type
          from table1 t1
         ) t1;
    

    或者更简单地说:

    select t1.*,
           sum( (box_type is distinct from prev_box_type)::int ) over (order by time) as count
    

    或者内置函数conditional_change_event()

    select t1.*,
           conditional_change_event(box_type) over (order by time) as count
    from table1 t1;
    

    【讨论】:

    • 我收到一个 SQL 编译错误。说它不是一个有效的按表达式分组
    • @Brad。 . .这是一个奇怪的错误。这些都没有使用group by。都是窗口函数。
    猜你喜欢
    • 2021-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-10
    相关资源
    最近更新 更多