728x90
문제
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.
https://www.hackerrank.com/challenges/symmetric-pairs/problem?isFullScreen=true
예시
Sample Input
Sample Output
20 20
20 21
22 23
문제 풀이
SELECT X, Y
FROM functions
WHERE X = Y
GROUP BY X, Y
HAVING COUNT(*) = 2
UNION
SELECT f1.X, f1.Y
FROM functions AS f1
INNER JOIN functions AS f2 ON f1.X = f2.Y AND f1.Y= f2.X
WHERE f1.X < f1.Y
ORDER BY X
SQL을 독학하시는 분들에게 도움이 되길 바라며,
혹 더 좋은 방법이 있거나 오류가 있다면 편하게 말씀 부탁드립니다.
728x90