MySQL/문제풀이
[HackerRank] Self JOIN: Symmetric Pairs
MINNI_
2021. 3. 15. 23:08
1. 문제
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
2. 답
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
3. KEY POINT
- UNION 위에 있는 곳에는 ORDER BY를 쓸 수 없음
- 마지막에 써야 함 => 마지막에 써야 UNION 된 테이블에서 ORDER BY를 할 수 있음. - 문제를 풀 때, 경우의 수를 나눠푸는 것을 생각하면 간단히 풀 수 있다.
www.hackerrank.com/challenges/symmetric-pairs/problem?h_r=internal-search
Symmetric Pairs | HackerRank
Write a query to output all symmetric pairs in ascending order by the value of X.
www.hackerrank.com