Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to SELECT two columns, where one column must be DISTINCT?

Tags:

sql

mysql

Table1 has 3 columns: col1, col2, col3

How can I SELECT all the DISTINCT values of col1 where col3 equals a certain value, then sort it by col2 DESC, yet have the distinct col1 results show their corresponding col2 value?

I tried the following but it did not work:

SELECT DISTINCT (col1), col2
FROM  `Table1` 
WHERE  `col3` =  'X'
ORDER BY  `col2` DESC 

The above does not result in distinct values of col1. If I remove ", col2", then it will show distinct values of col1, but it won't show me their corresponding col2 values.

So how do I do it?

like image 443
ProgrammerGirl Avatar asked Apr 24 '12 15:04

ProgrammerGirl


1 Answers

Perhaps something like this:

SELECT col1, MAX(col2) col2_max
FROM Table1
WHERE col3 = 'X'
GROUP BY col1
ORDER BY col2_max

?

You can play with it in this SQL Fiddle.

like image 176
Branko Dimitrijevic Avatar answered Oct 05 '22 23:10

Branko Dimitrijevic