일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | |||||
3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 |
31 |
Tags
- LeetCode
- lv4
- import re
- 파이썬
- hackerrank
- Growth hacking
- python
- lambda
- 코테
- coding
- Stack
- tableau
- programmers
- Level2
- cte
- level4
- sql
- itertools
- time complexity
- 코딩테스트
- AARRR
- 완전탐색
- coding test
- 프로그래머스
- counter
- join
- 코딩
- mysql
- 조합
- Queue
Archives
- Today
- Total
ror_coding
[HackerRank] Symmetric Pairs 본문
728x90
20 20이 self join하는 예외 케이스 나눠서 풀기 !
Question
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
Point
- 20 20이 하나만 있을 때 서로 self join해서 20 20 20 20 이 되는 문제점 존재.
- -> X,Y가 같을 때 케이스를 따로 group by - count를 이용해서 2개 이상일 때 출력.
Code
SELECT X, Y -- 20 20이 하나만 있을 때 SELF JOIN 되는 케이스 방지.
FROM FUNCTIONS
WHERE X = Y
GROUP BY X, Y
HAVING COUNT(*) >= 2
UNION
SELECT F1.X, F1.Y
FROM FUNCTIONS F1
JOIN FUNCTIONS F2 ON (F1.X = F2.Y) AND (F1.Y = F2.X)
WHERE F1.X < F1.Y
ORDER BY 1
now me

728x90
'Coding Test > SQL' 카테고리의 다른 글
[HackerRank] The Report (0) | 2025.06.14 |
---|---|
[HackerRank] Type of Triangle (0) | 2025.06.14 |
[HackerRank] Binary Tree Nodes (0) | 2025.04.05 |
[HackerRank] Occupations (0) | 2025.04.05 |
[Programmers Lv.5] 멸종위기의 대장균 찾기 - 301651 (0) | 2025.01.16 |