[HackerRank] Symmetric Pairs

mzzzi·2022년 4월 25일
0

HackerRank SQL

목록 보기
52/52
post-thumbnail

MySQL > Symmetric Pairs


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

My Answer


SELECT F1.X, F1.Y
FROM FUNCTIONS F1 JOIN FUNCTIONS F2 ON F1.X = F2.Y AND F1.Y = F2.X
GROUP BY F1.X, F1.Y -- 셀프조인하였으므로 중복값 제거
HAVING COUNT(F1.X) > 1 OR F1.X < F1.Y -- 중복 row 제거
ORDER BY F1.X;
profile
무럭무럭 성장하라🌳

0개의 댓글