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.
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,...)
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).
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.
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With