SQL & DB/HackerRank SQL Problem

[HackerRank SQL] Symmetric Pairs

YSY^ 2021. 3. 1. 21:30

www.hackerrank.com/challenges/symmetric-pairs/problem

 

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


Answer

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

f2(x2), f2(y2)를 추가해서 비교한다.

1개 이상이거나 y가 더큰 경우 출력한다.

Result

728x90
반응형