Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Distinct pair of values SQL

Consider

 create table pairs ( number a, number b )  

Where the data is

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

Etc.

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

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

only

I've tried

select distinct ( a ) , b from pairs group by b  

but gives me "not a group by expression"

like image 897
OscarRyz Avatar asked Aug 25 '09 20:08

OscarRyz


People also ask

How do you find distinct pairs in SQL?

To get the identical rows (based on two columns agent_code and ord_amount) once from the orders table, the following SQL statement can be used : SQL Code: SELECT DISTINCT agent_code,ord_amount FROM orders WHERE agent_code='A002';

Can we use multiple distinct in SQL?

Answer. Yes, the DISTINCT clause can be applied to any valid SELECT query. It is important to note that DISTINCT will filter out all rows that are not unique in terms of all selected columns.

How can I get distinct values of all columns in SQL?

To get unique or distinct values of a column in MySQL Table, use the following SQL Query. SELECT DISTINCT(column_name) FROM your_table_name; You can select distinct values for one or more columns.


2 Answers

What you mean is either

SELECT DISTINCT a, b FROM pairs; 

or

SELECT a, b FROM pairs GROUP BY a, b; 
like image 53
Michael Krelin - hacker Avatar answered Oct 05 '22 07:10

Michael Krelin - hacker


If you want to want to treat 1,2 and 2,1 as the same pair, then this will give you the unique list on MS-SQL:

SELECT DISTINCT      CASE WHEN a > b THEN a ELSE b END as a,     CASE WHEN a > b THEN b ELSE a END as b FROM pairs 

Inspired by @meszias answer above

like image 42
StuartQ Avatar answered Oct 05 '22 09:10

StuartQ