Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL distinct for 2 fields in a database

Tags:

sql

distinct

Can you get the distinct combination of 2 different fields in a database table? if so, can you provide the SQL example.

like image 737
leora Avatar asked Oct 10 '08 20:10

leora


People also ask

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

Select with distinct on all columns of the first query. Select with distinct on multiple columns and order by clause. Count() function and select with distinct on multiple columns.

Can we use distinct on 2 columns?

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.

Does distinct apply to all columns?

Yes, DISTINCT works on all combinations of column values for all columns in the SELECT clause.

Can you use distinct twice in SQL?

No you can't use that, it will throw an error, but there are other alternatives where you can get your desired results.


2 Answers

How about simply:

select distinct c1, c2 from t 

or

select c1, c2, count(*) from t group by c1, c2 
like image 55
Howard Pinsley Avatar answered Sep 19 '22 17:09

Howard Pinsley


If you want distinct values from only two fields, plus return other fields with them, then the other fields must have some kind of aggregation on them (sum, min, max, etc.), and the two columns you want distinct must appear in the group by clause. Otherwise, it's just as Decker says.

like image 22
Jeffrey L Whitledge Avatar answered Sep 16 '22 17:09

Jeffrey L Whitledge