Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
348 views
in Technique[技术] by (71.8m points)

sql - How can i select first record of each distinct couple of 2 columns

I have a table where i can have records like this:

ID ColA ColB
1 10 11
2 11 10
3 12 10
4 10 12

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You may use ROW_NUMBER here along with least/greatest logic:

WITH cte AS (
    SELECT *, ROW_NUMBER() OVER (PARTITION BY
                                     CASE WHEN ColA <= ColB THEN ColA ELSE ColB END,
                                     CASE WHEN ColA > ColB  THEN ColA ELSE ColB END
                                 ORDER BY ID) rn
    FROM yourTable
)

SELECT ID, ColA, ColB
FROM cte
WHERE rn = 1;

screen capture from demo link below

Demo

Explanation:

The two CASE expressions which appear in the partition clause of ROW_NUMBER find the smallest and greatest of the two columns ColA and ColB, for each record. So, we partition on the pair of least/greatest of the two columns, and then retain the record for each pair having the smallest ID value.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...