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
'SQL > MySQL 문제풀이' 카테고리의 다른 글
[HackerRank] Placements Solution(풀이 2가지) (0) | 2022.05.29 |
---|---|
[HackerRank] The Report Solution(풀이) (0) | 2022.05.29 |
[Leetcode] Rising Temperature Solution(풀이) (0) | 2022.05.24 |
[Leetcode] Employees Earning More Than Their Managers (풀이) (0) | 2022.05.24 |
[SQL LEFT JOIN][Leetcode] Customer Who Never Order (풀이) (0) | 2022.05.23 |