SQL/MySQL 문제풀이
[HackerRank] Symmetric Pairs Solution(풀이)
혜린티나
2022. 5. 29. 18:19
Symmetric Pairs | HackerRank
Write a query to output all symmetric pairs in ascending order by the value of X.
www.hackerrank.com
문제
You are given a table, Functions, containing two columns: X and Y.
Two pairs (X1, Y1) and (X2, Y2) are said to be symmetric pairs if X1 = Y2 and X2 = Y1.
Write a query to output all such symmetric pairs in ascending order by the value of X. List the rows such that X1 ≤ Y1.
Sample Input
Sample Output
20 20
20 21
22 23
문제 풀이
x = y 와 x <> y 인 경우를 나눠서 쿼리를 만들고 UNION으로 합치기
* 중복되는 결과값이 없기 때문에 UNION ALL도 동일한 결과나옴
SELECT X,Y
FROM Functions
WHERE X = Y
GROUP BY X, Y
HAVING COUNT(*) >= 2
UNION
SELECT f1.x, f1.y
FROM Functions f1
INNER JOIN Functions f2 ON f1.x = f2.y AND f1.y = f2.x
WHERE f1.x < f1.y
ORDER BY x