我有下表:
create table test_seq (id int, obs int);
insert into test_seq values (1,1);
insert into test_seq values (2,1);
insert into test_seq values (3,1);
insert into test_seq values (4,0);
insert into test_seq values (5,0);
insert into test_seq values (6,1);
insert into test_seq values (7,1);
insert into test_seq values (8,0);
insert into test_seq values (9,0);
insert into test_seq values (10,1);
insert into test_seq values (11,0);
有SQL方法,如何创建以下输出?
id obs seq_num
1 1 1
2 1 1
3 1 1
4 0 2
5 0 2
6 1 3
7 1 3
8 0 4
9 0 4
10 1 5
11 0 6
每当列obs中的值与前一行(按id排序)相比更改时,seq_num增加1。我可以在Excel中轻松解决这个问题(使用简单的if公式),但在postgres中无法解决这个问题。
答案 0 :(得分:2)
使用分析函数,例如:
select id, obs, sum(cnt) over (order by id) as seq_num
from (
select id, obs, case when obs <> (lag(obs) over (order by id)) then 1 else 0 end as cnt
from test_seq
)
order by id;
答案 1 :(得分:1)
我已经明白了:
with t as (
select
id,
obs,
case when lag(obs,1) over (order by id) <> obs then 1 else 0 end as test
from
tmp.test_seq
)
select
*,
sum(test) over (order by id rows between unbounded preceding and current row) + 1
from
t
答案 2 :(得分:0)
您可以使用rownumber来执行此操作。