首先,我們需要的,如果在 「顏色」,以找出兩個「IDS 「 是相同的。以下查詢完成color
上的完整外部聯接,然後通過id
進行彙總。如果兩個id
■找顏色相同,則全外連接總是匹配 - 有沒有空值:
select s1.id, s2.id
from s s1 full outer join
s s2
on s1.color = s2.color
group by s1.id, s2.id
having sum(case when s1.color is null then 1 else 0 end) = 0 and
sum(case when s2.color is null then 1 else 0 end) = 0
使用同樣的思路,我們可以將最小s1.id作爲的「身份證」組。這組ID,然後爲我們提供了所需的最終聚合的信息:
select s3.groupid, sum(s3.quantity) as quantity, s3.color as color
from (select min(s1.id) as groupid, s2.id
from (select s1.id, s2.id
from s s1 full outer join
s s2
on s1.color = s2.color
group by s1.id, s2.id
having sum(case when s1.color is null then 1 else 0 end) = 0 and
sum(case when s2.color is null then 1 else 0 end) = 0
) ss
group by s2.id
) sg join
s s3
on sg.id = s.id
group by sg.groupid, s3.color
在DB2中,您還可以使用listagg
做到這一點。首先,你需要得到的顏色列表中找出共性,然後使用它:
select min(s.id) as groupid, sum(s.quantity) as quantity, s.color
from (select id, listagg(color order by color) as thegroup
from s
group by id
) sg join
s
on sg.id = s.id
group by sg.thegroup, s.color
這可能是比第一個解決方案更有效。
請通過添加適當的標籤(Oracle,SQL Server,MySQL等)來指定您要定位的RDBMS。可能會有利用不被普遍支持的語言或產品功能的答案。此外,通過使用特定的RDBMS標記它,您的問題可能會得到更適合回答的人的關注。 – Taryn
你樣本數據中的「*相同外鍵*」在哪裏? –