Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select column value where other column is max of group

Tags:

sql

group-by

max

I am trying to select two columns into a table (ID and state). The table should show the state with the maximum value for each ID. I've tried a few other examples but nothing seems to work.

Original data structure:

ID  state    value (FLOAT) 1   TX   921,294,481  1   SC   21,417,296  1   FL   1,378,132,290  1   AL   132,556,895  1   NC   288,176  1   GA   1,270,986,631  2   FL   551,374,452  2   LA   236,645,530  2   MS   2,524,536,050  2   AL   4,128,682,333  2   FL   1,503,991,028 

The resulting data structure should therefore look like this:

ID  STATE (Max Value) 1   FL 2   AL 

Florida and Alabama having the largest values in their ID groups.

Any help would be greatly appreciated on this. I did find a SO answer here already, but could not make the answers work for me.

like image 998
Richard Todd Avatar asked Jan 10 '13 09:01

Richard Todd


People also ask

How do I get the maximum value from another column of a table in SQL?

The MySQL Solution If you're working with MySQL, you can combine MAX() with the GREATEST() function to get the biggest value from two or more fields. Here's the syntax for GREATEST: GREATEST(value1,value2,...)

How do you get a record with maximum value for each group?

MySQL MAX() function with GROUP BY retrieves maximum value of an expression which has undergone a grouping operation (usually based upon one column or a list of comma-separated columns).

Can we use MAX function in WHERE clause?

Overview. The MAX() function is used with the WHERE clause to gain further insights from our data. In SQL, the MAX() function computes the highest or maximum value of numeric values in a column.

Which query can be used to extract the maximum value of the column?

SQL MIN() and MAX() Functions The MIN() function returns the smallest value of the selected column. The MAX() function returns the largest value of the selected column.


2 Answers

For SQL Server (and other products with windowed functions):

SELECT * FROM (    SELECT      *,      ROW_NUMBER() OVER (PARTITION BY ID ORDER BY value desc) as rn    FROM      UnnamedTable ) t WHERE    t.rn = 1 
like image 122
Damien_The_Unbeliever Avatar answered Sep 28 '22 07:09

Damien_The_Unbeliever


You can use a subquery to get this result:

select t1.id, t1.[state] MaxValue from yourtable t1 inner join (   select id, max(value) MaxVal   from yourtable   group by id ) t2   on t1.id = t2.id   and t1.value = t2.maxval order by t1.id 

See SQL Fiddle with Demo

like image 36
Taryn Avatar answered Sep 28 '22 09:09

Taryn