𝙎𝙌𝙇

[HackerRank] Symmetric Pairs

콜라맛갈비 2023. 8. 2. 19:34
728x90

https://www.hackerrank.com/challenges/symmetric-pairs/problem?isFullScreen=true 

 

Symmetric Pairs | HackerRank

Write a query to output all symmetric pairs in ascending order by the value of X.

www.hackerrank.com

 

symmetric pairs는 x1 = y2 and x2 = y1인 쌍을 의미함.

x1 <= y2 인 열만 적어주면 됨. (Ex. 20, 21의 경우, 21, 20은 출력하지 않기)

x 컬럼 기준으로 오름차순 정렬.

 

 

 

SELECT sub.X, sub.Y
FROM (SELECT if(X <= Y, X , Y) as X, if(X <= Y, Y , X) as Y
      FROM Functions) sub
GROUP BY sub.X, sub.Y
HAVING count(*) >= 2
ORDER BY sub.X

 

 

(
# x! = y
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 


UNION

# x = y
SELECT X,Y
FROM Functions
WHERE X=Y
GROUP BY X,Y
HAVING count(*) > 1
)

ORDER BY X

 

728x90

'𝙎𝙌𝙇' 카테고리의 다른 글

[HackerRank] Weather Observation Station 5  (0) 2023.08.09
[HackerRank] Interviews  (0) 2023.08.03
[HackerRank] Placements  (0) 2023.07.27
[HackerRank] SQL Project Planning  (0) 2023.07.26
[HackerRank] Contest Leaderboard  (0) 2023.07.13