2016-05-15 23 views
2

的斷言說我有幾行(按日期排序),其中一列包含以下數據:SQL - 在一個有序的一系列數字

1 
1 
1 
0 
0 
1 
0 
1 
1 
1 

等 如何選擇1秒的計數,直到下一個0達到,然後重置計數器。例如,查詢應該返回了以下數據:

1 
1 
1 3 
0 
0 
1 1 
0 
1 
1 
1 3 

其實,我並不需要實際的數據,我確定如果查詢只返回彙總/計數。我只是列入第一列以便於理解。 我正在運行PostgreSQL 9.5。但是,如何解決其他數據庫的問題會很有趣。

感謝

+0

是否有任何其他列指定順序的序列? –

+0

嗨,是的,類似於ORDER BY日期 – Davita

+1

您需要一個指定排序的列。默認情況下,SQL表是無序的。 –

回答

1

在這個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 

輸出 enter image description here

0

下面是SQL Server 2008 R2的部分解決方案,但在其他數據庫應該實現。 ones是您的原始表,其中包含反映數據順序(1,2,3等)的id關鍵字段。 flag保存10條目。它通過對每行之前出現的包含標誌= 0的行進行計數來對數據進行分組。每次運行1都會計入越來越多的零,因此您可以使用它來唯一標識每次運行1。 它不提供運行計數,但會給您每次運行1 s的總結計數。

create table ones_summary (PreviousZeros int) 

insert ones_summary 
select (select count(*) as N from ones t2 where t2.id < t1.id and t2.flag = 0) as PreviousZeros 
from ones t1 
where t1.flag = 1 

select PreviousZeros, count(*) 
from ones_summary 
group by PreviousZeros 
相關問題