Det er altid en smule vanskeligt at identificere ikke-konsekutive værdier og involverer flere indlejrede underforespørgsler (jeg kan i det mindste ikke komme med en bedre løsning).
Det første trin er at identificere ikke-konsekutive værdier for året:
Trin 1) Identificer ikke-konsekutive værdier
select company,
profession,
year,
case
when row_number() over (partition by company, profession order by year) = 1 or
year - lag(year,1,year) over (partition by company, profession order by year) > 1 then 1
else 0
end as group_cnt
from qualification
Dette returnerer følgende resultat:
company | profession | year | group_cnt ---------+------------+------+----------- Google | Programmer | 2000 | 1 Google | Sales | 2000 | 1 Google | Sales | 2001 | 0 Google | Sales | 2002 | 0 Google | Sales | 2004 | 1 Mozilla | Sales | 2002 | 1
Nu med group_cnt-værdien kan vi oprette "gruppe-id'er" for hver gruppe, der har på hinanden følgende år:
Trin 2) Definer gruppe-id'er
select company,
profession,
year,
sum(group_cnt) over (order by company, profession, year) as group_nr
from (
select company,
profession,
year,
case
when row_number() over (partition by company, profession order by year) = 1 or
year - lag(year,1,year) over (partition by company, profession order by year) > 1 then 1
else 0
end as group_cnt
from qualification
) t1
Dette returnerer følgende resultat:
company | profession | year | group_nr ---------+------------+------+---------- Google | Programmer | 2000 | 1 Google | Sales | 2000 | 2 Google | Sales | 2001 | 2 Google | Sales | 2002 | 2 Google | Sales | 2004 | 3 Mozilla | Sales | 2002 | 4 (6 rows)
Som du kan se har hver "gruppe" sit eget group_nr, og dette kan vi endelig bruge til at aggregere ved at tilføje endnu en afledt tabel:
Trin 3) Endelig forespørgsel
select company,
profession,
array_agg(year) as years
from (
select company,
profession,
year,
sum(group_cnt) over (order by company, profession, year) as group_nr
from (
select company,
profession,
year,
case
when row_number() over (partition by company, profession order by year) = 1 or
year - lag(year,1,year) over (partition by company, profession order by year) > 1 then 1
else 0
end as group_cnt
from qualification
) t1
) t2
group by company, profession, group_nr
order by company, profession, group_nr
Dette returnerer følgende resultat:
company | profession | years ---------+------------+------------------ Google | Programmer | {2000} Google | Sales | {2000,2001,2002} Google | Sales | {2004} Mozilla | Sales | {2002} (4 rows)
Hvilket er præcis, hvad du ville, hvis jeg ikke tager fejl.