Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SELECT DISTINCT pair of COLUMN in SQL

Tags:

sql

Consider

create table pairs ( number a, number b )

Where the data is

1,4
4,1
2,4
2,4
3,2
3,2
2,3
5,1
Etc.

I'm Getting this

1,4
4,1
2,4
3,2
2,3
5,1

What query gives me the distinct values the number column b has So I can see

1,4
5,1
2,4
3,2

only

I don't want the value in column a should be present in column b. Please help.

what i need is to select distinct values on both sides of column. for eg. if (1,2) is present then (2,1) must not be present

like image 673
user3418795 Avatar asked Mar 14 '14 07:03

user3418795


1 Answers

You didn't state your DBMS, but this works on many DBMS (least and greatest aren't part of the SQL standard unfortunately)

select distinct least(a,b), greatest(a,b)
from pairs
like image 88
a_horse_with_no_name Avatar answered Nov 03 '22 00:11

a_horse_with_no_name