假设我有几行(按日期排序),其中一列包含以下数据:
1
1
1
0
0
1
0
1
1
1
等。
如何选择1s的计数,直到达到下一个0,然后重置计数器。例如,查询应返回以下数据:
1
1
1 3
0
0
1 1
0
1
1
1 3
实际上,我不需要实际的数据,如果查询只返回aggregate/count,我就可以了。为了更容易理解,我只加入了第一栏。
我在运行PostgreSQL 9.5。然而,对于其他DBs来说,如何解决这个问题也是有趣的。
谢谢
最佳答案
在这个SQL中,我假设列c1是日期的序列
drop table if exists t5;
create table t5 (c1 int primary key, c2 int);
insert into t5 values (1, 1);
insert into t5 values (2, 1);
insert into t5 values (3, 1);
insert into t5 values (4, 0);
insert into t5 values (5, 0);
insert into t5 values (6, 1);
insert into t5 values (7, 0);
insert into t5 values (8, 1);
insert into t5 values (9, 1);
insert into t5 values (10, 1);
select grp, max(cnt) from (
with recursive t(id, cnt, grp) as (
select c1, c2, 1
from t5
where c1 = 1
union all
select c1,
-- if next is 1 increment existing count else set it to zero
case when b.c2 = 1 then cnt+1 else 0 end,
-- if 0 change group else retain group [0 to 1 will retain group]
-- as long as '1' to '0' changes the group we are good
case when b.c2 = 1 then grp else grp+1 end
from t5 b, t
where b.c1 = id + 1
)
select * from t
) t group by grp having max(cnt) > 0 order by grp
输出