添加一列,当另一列更改时,该列会递增

时间:2013-11-11 12:56:45

标签: sql postgresql

我有像

这样的表格
id status other columns
-- ------ -------------
1  f
2  f
3  t
4  t
5  t
6  f

现在,当我选择表格时,我想添加特定列并检查状态何时发生变化。结果应该是这样的:

id status other columns status_index
-- ------ ------------- ------------
1  f                         1
2  f                         1
3  t                         2
4  t                         2
5  t                         2
6  f                         3

查询应该是postgres。

1 个答案:

答案 0 :(得分:2)

with cte as (
    select
        *,
        row_number() over(order by id) as rn1,
        row_number() over(partition by status order by id) as rn2
    from Table1
)
select
    id, status,
    dense_rank() over(order by rn1 - rn2) as status_index
from cte
order by id

<强> sql fiddle demo