Symmetric Pairs

  • + 1 comment

    First, we can divide the problem into smaller parts. We want to compare all pairs and find the sy pairs. We can use a cross join to compare the pairs with the required conditions. However, there are two problems with this approach.

    First, if we compare all pairs and get all sy pairs, the results may have duplicates. For example, the pair (20, 20) would appear twice in the results. We can use the distinct keyword to exclude the duplicates.

    Second, if we have the pair (20, 20) only once in the dataset, it will still be included in the final results as a sy pair if we compare it with itself. We can solve this problem by not comparing the pair with itself. Another solution is to use the count function to count the number of times each pair appears in the results. If the count is 1, then the pair is not a sy pair.

    WITH t AS (SELECT *, row_number() over( ORDER BY X) AS roN FROM functions) SELECT DISTINCT t.X, t.Y FROM t INNER JOIN t t1 ON t.X = t1.Y AND t.Y = t1.X AND t.X <= t.y AND t.roN <> t1.roN ORDER BY t.X