Milky's note

[HackerRank](M) Symmetric Pairs 본문

SQL/SQL 코딩 테스트-HackerRank

[HackerRank](M) Symmetric Pairs

밀뿌 2022. 4. 6. 15:36

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

 

[문제]

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

 

 

[답]

- mysql

select f1.x, f1.y from functions f1
join functions f2
on f1.x=f2.y and f2.x=f1.y
group by f1.x, f1.y
having count(*) > 1 or f1.x < f1.y
order by f1.x

이 문제는 self join으로 풀 수 있다.

이름은 거창하지만 똑같은 join문에 자기 자신을 join 하면된다.

문제에서 준 조건으로 join을 해주었고 출력의 중복을 방지하기 위해서 group by를 수행하였다.

그리고 x=y인 조건, x<y을 찾기 위해 having 절을 사용해서 나타내었다.

하나의 컬럼이 아닌 쌍을 기준으로 찾아야하기 때문에 count가 2이상인 것들은 x=y 조건을 만족한다.

그래서 count(*) > 1을 해주었고, x<y인 조건과 둘 중 하나를 만족해야하기 때문에 or로  x < y 조건을 추가해주었다.

정렬은 x를 기준으로 오름차순을 해주라고 문제가 나와있어서 x를 기준으로 오름차순을 진행하였다.

Comments