첫째, 우리는이에 대해 "색상"있는지 확인해야합니다 "IDS "동일합니다. 다음 쿼리는 color
에서 전체 외부 조인을 수행 한 다음 id
까지 집계합니다. 이 개 id
의이 같은 색이있는 경우, 다음 전체 외부는 항상 일치에 가입 - 더 널 (NULL)이 없습니다 : 같은 생각을 사용하여
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
, 우리는의 "ID"로 최소 s1.id을 할당 할 수 있습니다 그룹. DB2에서
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
당신은 또한 listagg
하여이 작업을 수행 할 수 있습니다 :이 그룹 ID는 우리에게 최종 집계에 필요한 정보를 제공합니다. 먼저 공통성을 확인하기 위해 색상 목록을 얻은 다음 사용하십시오.
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
샘플 데이터에서 "* 동일한 외래 키 *"는 어디에 있습니까? –