Question

my table lools like this:

name    | var
----------------
Joe     | 3
Liz     | 1
Liz     | 4
Joe     | 2
Peter   | 3
Joe     | 7
Liz     | 2

I am looking for a MYSQL query that will give me the DISCTINCT names of column name with the highest var related to the name. So, for the example above, I am looking for

Joe   | 7
Liz   | 4
Peter | 3

my try was:

SELECT name, var 
FROM table
GROUP BY name
ORDER BY var DESC

I tried, too,

SELECT DISTINCT name, var

or

SELECT DISTINCT(name), var

but with those I got distinct combinations of name,var

Was it helpful?

Solution

You need to use the aggregate function MAX() to get what you want with GROUP BY:

SELECT name, MAX(var) as var
FROM table
GROUP BY name
ORDER BY name ASC

... the ORDER BY clause is optional in this case.

OTHER TIPS

try this

select name, max(var) as maxvar from Table1
group by name
ORDER BY maxvar DESC

DEMO HERE

SELECT NAME, MAX(VAR) as var FROM XYZ GROUP BY NAME

--- Example: you have SELECT NAME, VAR FROM XYZ

Name  |  var
Mustafa  6
Tim      4
Tim      7
Joey     3
Tim      5
Joey     8
Mustafa  12

Now after using the Grouping function you will get the following, which is a result of the GROUP BY function. It does not take care about the other columns and its values. So you might have some random numbers here.

SELECT NAME, VAR FROM XYZ GROUP BY NAME

Name  |  var
Tim      5
Joey     3
Mustafa  12     <-- only this record ok?!

---- Now we use MAX() for our "var" field. so it always searches for all the records within our groups for the MAX() value. If you would like to, you could add an Order statement for the MAX() Value. ( ORDER BY MAX(VAR) )

SELECT NAME, MAX(VAR) as var FROM XYZ GROUP BY NAME

Name  |  var
Tim      7
Joey     8
Mustafa  12
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top