Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

sql - Get pair-wise single row

I have some data in a MS SQL Server database. Sample data is:

Sl ColumnA ColumnB
1 111 112
2 112 111
3 113 114
4 114 113
5 115 116
6 116 115
question from:https://stackoverflow.com/questions/65882003/get-pair-wise-single-row

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

1 Answer

0 votes
by (71.8m points)

One approach is to use CASE expressions to find the least/greatest value in each record:

SELECT DISTINCT
    CASE WHEN ColumnA < ColumnB  THEN ColumnA ELSE ColumnB END AS ColumnA,
    CASE WHEN ColumnA >= ColumnB THEN ColumnA ELSE ColumnB END AS ColumnB
FROM yourTable
ORDER BY 1;

screen capture from demo link below

Demo

Note that in certain other databases (such as MySQL and Postgres), there are formal LEAST and GREATEST functions, which can simplify and eliminate the need for the bulky CASE expressions used above.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...