[英]Postgres recursive CTE with Group?
我試圖找出masterIds作為數組。 請在下面找到
create temp table location as
select 1 as id,'World' as name,null as main_id
union all
select 2,'Asia',1
union all
select 3,'Africa',1
union all
select 4,'India',2
union all
select 5,'Sri Lanka',2
union all
select 6,'Mumbai',4
union all
select 7,'South Africa',3
表如
ID | 姓名 | 主要標識 |
---|---|---|
1 | 世界 | null |
2 | 亞洲 | 1 |
3 | 非洲 | 1 |
4 | 印度 | 2 |
5 | 斯里蘭卡 | 2 |
6 | 孟買 | 4 |
7 | 南非 | 3 |
8 | 開普敦 | 7 |
我的預期結果如下:
ID | 姓名 | 主要標識 | MasterIds Arrayint |
---|---|---|---|
1 | 世界 | null | 1 |
2 | 亞洲 | 1 | 1,2 |
3 | 非洲 | 1 | 1,3 |
4 | 印度 | 2 | 1,2,4 |
5 | 斯里蘭卡 | 2 | 1,2,5 |
6 | 孟買 | 4 | 1,2,4,6 |
7 | 南非 | 3 | 1,3,7 |
8 | 開普敦 | 7 | 1,3,7,8 |
而且我的代碼只處理一行,但我需要整個表格。 請在下面找到我的代碼:
with recursive
cte as (
select * from location where id=4
union all
select g.* from cte join location g on g.id = cte.main_id
)
select array_agg(id) from cte l
您似乎想要每個 id 的所有祖先(包括 id)的數組。 這是一種嘗試:
with recursive cte as (
select id, name, main_id from location
union all
select cte.id, g.name, g.main_id
from cte join location g on g.id = cte.main_id
)
select id, array[id] || array_agg(main_id)
from cte l
where main_id is not null
group by id
見小提琴
對於遞歸 cte 中的每次迭代,我們保留我們開始的 id 並向上遍歷樹(即,將下一個祖先添加到祖先集合中)。 最后,我們為每個 id 創建一個組,並將所有祖先聚合到數組中。
值得注意的是,祖先的集合是無序的,因此您最終可能會得到一個無序的“路徑”。 您可以通過提供訂單來解決這個問題,這里我使用相對於 id 的級別:
with recursive
cte as (
select id, name, main_id, 0 as lvl from location
union all
select cte.id, g.name, g.main_id, lvl+1 from cte join location g on g.id = cte.main_id
)
select id, array[id] || array_agg(main_id order by lvl)
from cte l
where main_id is not null
group by id
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.