问题描述
我正在尝试编写一个查询,在该查询中我根据其他条件更新计数器。例如:
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 | 标识符 |
---|---|
小 | 1 |
小 | 1 |
小 | 1 |
中等 | 2 |
中等 | 2 |
大 | 3 |
大 | 3 |
小 | 4 |
谢谢!
解决方法
您的问题仅在您有一列用于排序的情况下才有意义。让我假设存在这样一个列——根据您的代码,我将其命名为 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