SQL Server How to Distinct Values from Different Columns in SQL

a5g8bdjr  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(110)

I got a table like :
| Column A | Column B |
| ------------ | ------------ |
| 13 | 24 |
| 24 | 13 |
| 16 | 89 |
| 89 | 16 |

Since they include the same values in different columns for example 16-89 89-16 doesn't make a difference for my table and they duplicate. Can you help me on how to remove them? What I wanna reach is

Column AColumn B
1324
1689

Or

Column AColumn B
2413
8916

Doesn't make any difference for my data. Thank you all.

I couldn't reach anything. I tried to Distinct data but it doesn't work anyway.

xiozqbni

xiozqbni1#

This can be done using LEAST and GREATEST :

SELECT DISTINCT LEAST(ColumnA, ColumnB) AS ColumnA, GREATEST(ColumnA, ColumnB) ColumnB
FROM mytable

Demo on sql server 2022

If LEAST and GREATEST are not supported :

SELECT DISTINCT IIF(ColumnA < ColumnB, ColumnA, ColumnB) AS ColumnA, -- LEAST
                IIF(ColumnA > ColumnB, ColumnA, ColumnB) AS ColumnB  -- GREATEST
FROM mytable

Demo here

相关问题