2017-06-16 79 views
0

我有如下表:組連續通過

SELECT * 
FROM mytable 
ORDER BY id; 

id name code time 
1 A  111  1 
2 A  111  2 
3 A  888  3 
4 A  888  4 
5 A  888  5 
6 A  888  6 
7 A  888  7 
8 A  111  8 
9 A  111  9 
10 A  111  10 

我需要得到這樣的結果:

name code times_between 
A  111  1,2 
A  888  3,7 
A  111  8,10 

是否有可能通過集團「塊」? 我需要根據時間做出區分,所以我不能只按名稱,代碼進行分組,只能得到第一個和最後一個元素。

+0

「的順序表」 ---哪有這回事。表中的數據是無序存儲的,並且不能保證是相同的,除非您明確地在查詢中使用ORDER BY。 – zerkms

+0

我編輯了這個問題。 – ruggfrancesco

+0

https://www.postgresql.org/message-id/[email protected]以及許多其他相關的東西,當你谷歌與「postgresql組連續」的請求。 – zerkms

回答

4

一種方法是這樣的:

with the_table(id, name , code , time) as(
select 1, 'A',111 , 1 union all 
select 2, 'A',111 , 2 union all 
select 3, 'A',888 , 3 union all 
select 4, 'A',888 , 4 union all 
select 5, 'A',888 , 5 union all 
select 6, 'A',888 , 6 union all 
select 7, 'A',888 , 7 union all 
select 8, 'A',111 , 8 union all 
select 9, 'A',111 , 9 union all 
select 10, 'A',111 , 10 
) 


select name, code, min(time) ||','|| max(time) from (
    select name, code, time, id, 
    row_number() over(order by id) - 
    row_number() over(partition by name , code order by id) as grp 
    from the_table 
) t 
group by name, code, grp 
order by min(id) 

(我忘了,只是無法找到/記得技術的名稱,它創建組grp

+0

如果我正確解釋問題,你應該使用'OVER(ORDER BY time)'。 –

+0

@LaurenzAlbe - 如果我正確理解,「間隙和島嶼」的順序取決於「id」列 –

+0

@OtoShavadze你說得對,順序取決於id。 您的回答很令人頭疼,非常感謝。 – ruggfrancesco