SQL

Symmetric Pairs

sawo11 2025. 5. 6. 01:20

문제 풀이 링크: 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


풀이 과정

 
  • data1, data2 CTE
    • functions 테이블을 두 번 조회
    • 각각의 쿼리에 ROW_NUMBER()를 사용하여 순서 배정 
  • 본 쿼리
    • DISTINCT: 같은 쌍이 중복 출력되는 것 방지
    • x1 = y2 AND y1 = x2
    • RN1 != RN2: 같은 행끼리 매칭되는 것 방지
    • x1 <= y1
WITH data1 AS(
SELECT f.x x1, f.y y1, ROW_NUMBER() OVER(ORDER BY f.x) RN1
FROM functions f
),

data2 AS(
SELECT f.x x2, f.y y2, ROW_NUMBER() OVER(ORDER BY f.x) RN2
FROM functions f
)

SELECT DISTINCT x1, y1
FROM data1
JOIN data2
    ON x1=y2 AND y1=x2 AND RN1 != RN2 AND x1 <= y1
ORDER BY x1;

'SQL' 카테고리의 다른 글

Ollivander's Inventory  (0) 2025.05.06
SQL Project Planning  (0) 2025.05.06
Weather Observation Station  (0) 2025.05.06
Top Competitors  (0) 2025.05.06
The Report  (0) 2025.05.05