我用這個爲例表:
create table temp (id int, val int)
insert into temp values (1,101),(1,102),(2,102),(2,104),(2,107)
insert into temp values (2,103)
insert into temp values (2,105)
insert into temp values (2,108)
insert into temp values (2,110)
這是你想要什麼:
select t1id,cnt, min(t1val) as min, max(t1val), count(t1val)
from (
select tt1.*,
(select count (*) from
(
select t1.id as t1id,
t1.val as t1val,
(select val from temp t2 where t1.id = t2.id and t2.val = t1.val+1) as t2val,
row_number() over (order by t1.id, t1.val) as rn
from temp t1
) tt2
where tt2.t2val is null and tt2.rn < tt1.rn
) cnt
from (
select t1.id as t1id,
t1.val as t1val,
(select val from temp t2 where t1.id = t2.id and t2.val = t1.val+1) as t2val,
row_number() over (order by t1.id, t1.val) as rn
from temp t1
) tt1
)ttt1
group by t1id, cnt
order by t1id, min
更新:如果表是無序修正了)
PostgreSQL的版本? (這與功能可用性有關,因此您應該始終指定它,例如,窗口函數和遞歸CTE僅在8.4中可用)。我也迴應克萊夫:你已經試過了什麼?你卡在哪裏? (順便說一句,「group」是一個關鍵字,因此也是一個可怕的名字)。 –
我試過在函數中使用循環,但似乎不太好。 一個朋友建議我使用遞歸,但我仍然不知道如何使用遞歸爲這種情況下 – nametal