(select q1.x, q1.y
from functions as q1
left join functions as q2 on q1.x = q2.y and q1.y = q2.x
where q1.x < q1.y
union
select x,y
from functions
where x = y
group by x,y
having count(*)>1)
order by x
처음에는 left join을 사용하여 풀려고 했다.
하지만 left join은
7 19 NULL NULL
한쪽에만 데이터가 존재한다면 위와 같이 output이 나오고
q1.x < q1.y의 조건에 맞기 때문에 최종 output에 들어간다.
따라서 left join이 아닌 inner join을 사용해야한다.
(select q1.x, q1.y
from functions as q1
inner join functions as q2 on q1.x = q2.y and q1.y = q2.x
where q1.x < q1.y
union
select x,y
from functions
where x = y
group by x,y
having count(*)>1)
order by x
union의 윗부분
x1과 y1가 같지 않을 경우의 output
union의 아랫부분
x1 = y1일 때, (x1, y1)의 쌍이 하나 더 있는 경우의 output
이거 푸는데 40분이 걸렸다.....
sql도 열심히 해야겠다.
'섭섭의 공부 > SQL' 카테고리의 다른 글
[HackerRank] Challenges (0) | 2021.12.23 |
---|---|
[HackerRank] Top Earners (0) | 2021.12.22 |
[LeetCode] Rising Temperature (0) | 2021.12.21 |
[LeetCode] Employees Earning More Than Their Managers (0) | 2021.12.02 |
[LeetCode] Customer Who Nerver Order (0) | 2021.12.02 |