본문 바로가기

SQL/HackerRank

[SQL] HackerRank: Symmetric Pairs

문제

 

You are given a table, Functions, containing two columns: 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.

 

-> 대칭되는 쌍이 있는 (x,y) 찾기

 

 

풀이

 

 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

 UNION

 SELECT x, y
 FROM functions 
 WHERE x=y 
 GROUP BY x
 HAVING COUNT(*)=2
 ORDER BY x

 

# x = y인 경우/ x ≠ y인 경우 따로따로 생각하여 작성 후 UNION 

 

# UNION에서 정렬(ORDER BY)는 마지막 쿼리에서 작성!!

   각각 SELECT마다 ORDER BY XXXX

'SQL > HackerRank' 카테고리의 다른 글

[SQL] HackerLank : Challenges  (0) 2023.06.10
[SQL] HarkerLank: Top Earners  (0) 2023.06.08
[SQL] HackerRank: INNER JOIN 문제  (0) 2023.05.31
[SQL] HakerRank: The Report  (0) 2023.05.31
[SQL] HackerRank : Weather Observation Station 3  (0) 2023.05.19