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
'MySQL > 문제풀이' 카테고리의 다른 글
[LeetCode] 595. Big Countries (0) | 2021.03.22 |
---|---|
[LeetCode] CASE 테이블 피봇 : 1179. Reformat Department Table (0) | 2021.03.15 |
[LeetCode] Self JOIN : 197. Rising Temperature (0) | 2021.03.15 |
[LeetCode] Self JOIN : 181. Employees Earning More Than Their Managers (0) | 2021.03.15 |
[LeetCode] LEFT JOIN : 183. Customers Who Never Order (0) | 2021.03.15 |
댓글