【问题标题】:Update statement within select statement选择语句中的更新语句
【发布时间】:2021-08-25 20:27:06
【问题描述】:

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

with table 1 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

我只想在 box_type 每次更改时递增该标识符值

谢谢!

【问题讨论】:

    标签: sql postgresql sql-update with-statement case-when


    【解决方案1】:

    只有当您有一个指定排序的列时,您的问题才有意义。让我假设存在这样一个列 - 根据您的代码,我将其命名为 time

    然后,您可以使用lag() 和累积和:

    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
    

    【讨论】:

    • 这很完美!我现在正试图将它放入雪花中。你知道如何把这个函数转换成合适的语法吗?
    • @Brad。 . .我刚刚为此回答了后续问题。
    猜你喜欢
    • 1970-01-01
    • 2016-04-24
    • 2020-04-03
    • 2018-01-22
    • 1970-01-01
    • 1970-01-01
    • 2013-06-07
    • 1970-01-01
    相关资源
    最近更新 更多