Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select distinct on specific columns

I have few columns in a table

Col1, Col2, Col3, Col4

Now I want to select like this

SELECT DISTINCT (Col1, Col2, Col3), Col4

i.e. get the distinct based on only these three colunms.

like image 650
Zerotoinfinity Avatar asked Sep 27 '12 11:09

Zerotoinfinity


People also ask

How do I get distinct on only one column?

Adding the DISTINCT keyword to a SELECT query causes it to return only unique values for the specified column list so that duplicate rows are removed from the result set.

Can you use select distinct with multiple columns?

In SQL multiple fields may also be added with DISTINCT clause. DISTINCT will eliminate those rows where all the selected fields are identical.

How can I get distinct values for a particular column 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. The column names has to be separated with comma.

How do I select all columns with distinct on one column?

SELECT DISTINCT FIELD1, FIELD2, FIELD3 FROM TABLE1 works if the values of all three columns are unique in the table. If, for example, you have multiple identical values for first name, but the last name and other information in the selected columns is different, the record will be included in the result set.


1 Answers

Just GROUP BY Col1, Col2, Col3 with an aggregate function with the col4 like MAX, MIN, etc .. like so:

SELECT Col1, Col2, Col3, MAX(Col4)
FROM TableName
GROUP BY Col1, Col2, Col3
like image 96
Mahmoud Gamal Avatar answered Oct 12 '22 08:10

Mahmoud Gamal