1

我确实有下表:

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 中无法解决这个问题。

4

3 回答 3

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;
于 2013-01-23T13:23:51.003 回答
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
于 2013-01-23T13:23:42.473 回答
0

您可以使用rownumber来做到这一点。

于 2013-01-23T13:18:13.980 回答