1

我有桌子

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 的。

4

1 回答 1

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

于 2013-11-11T14:26:00.670 回答