We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
- Prepare
- SQL
- Advanced Join
- Symmetric Pairs
- Discussions
Symmetric Pairs
Symmetric Pairs
Sort by
recency
|
1480 Discussions
|
Please Login in order to post a comment
SELECT F1.X, F1.Y
FROM Functions AS F1
INNER JOIN Functions AS F2
ON F1.X = F2.Y AND F2.X = F1.Y
WHERE F1.X <= F1.Y
GROUP BY F1.X, F1.Y
HAVING (COUNT(F1.X) > 1 AND F1.X = F1.Y) OR (F1.X <> F1.Y)
ORDER BY F1.X;
This SQL query identifies symmetric pairs (X, Y) and (Y, X) by performing a self JOIN, ensuring that each pair appears only once using WHERE X ≤ Y. It also correctly handles reflexive pairs (X = Y), ensuring they are included only if they appear more than once in the table. The GROUP BY removes duplicates, and the ORDER BY X ASC ensures results are sorted properly. """ SELECT f1.x, f1.y FROM functions AS f1 INNER JOIN functions AS f2 ON f1.x = f2.y AND f2.x = f1.y AND ( f1.x <> f1.y OR ( SELECT count(*) FROM functions f WHERE f.x = f1.x AND f.y = f1.y ) > 1 ) WHERE f1.x <= f1.y GROUP BY f1.x, f1.y ORDER BY f1.x ASC;
"""" Using the self JOIN ensures that we correctly match symmetric pairs (X, Y) and (Y, X), which a simple WHERE condition cannot achieve. The WHERE X ≤ Y condition prevents duplicate pairs from appearing in different orders. The reflexive pair check (X = Y) with COUNT(*) > 1 ensures that values like (30, 30) are included only if they appear more than once. The GROUP BY eliminates redundancies, and ORDER BY X ASC improves readability.
SELECT X,Y FROM FUNCTIONS WHERE X<=Y GROUP BY X,Y ORDER BY X ASC
PLEASE CORRECT ME
I have no idea why we have to group by, it is a purely bad question
In this sql, I can't find the condition that we have to write only one row about same diagonal pairs this sql is answer. but i can't understand why i have to use group by `with cte as ( select x, y, row_number() over (order by x) as rn from functions ) select f1.x, f1.y from cte f1 join cte f2 on f1.x = f2.y and f1.y = f2.x and f1.rn != f2.rn where f1.x <= f1.y group by f1.x, f1.y