select 语句中的更新语句

Update statement within select statement

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

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

这是我正在尝试做的事情的基本内容。我想要一个看起来像这样的 table:

box_type 标识符
1
1
1
2
2
3
3
4

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

谢谢!

您的问题只有在您有一个列来区分排序时才有意义。让我假设存在这样一个列——根据您的代码,我将其命名为 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