HackerRank_prepare_sql_advanced_join_2

nowhere·2022년 1월 17일
0

문제

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.

문제 해석

  1. 테이블의 데이터 (x,y) 쌍들 중에 (x1,y1), (x2,y2)에 대하여 x1 = y2 그리고 y1 = x2 가 되는 대칭쌍을 찾아라.
  2. x<=y인 (x,y) 쌍을 출력하고 x값을 기준으로 오름차순으로 정렬해라

문제 분석

  • self join을 통해 대칭이 되는 쌍을 구할 수 있다.
  • 하지만 x와 y의 값이 같으면 2개의 행이 없어도 join을 통해 쌍이 만들어진다.
    • 예외처리 필요

정답

select f1.x,f1.y from functions as f1
join functions as f2 on f1.x = f2.y and f1.y = f2.x
where f1.x<=f1.y
group by f1.x, f1.y
having count(*)>1 or f1.x < f1.y
order by f1.x;
profile
수익성은 없으니 뭐라도 적어보는 벨로그

0개의 댓글