Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select max value of each group

Tags:

sql

Name    Value   AnotherColumn ----------- Pump 1  8000.0  Something1 Pump 1  10000.0 Something2 Pump 1  10000.0 Something3 Pump 2  3043    Something4 Pump 2  4594    Something5 Pump 2  6165    Something6 

My table looks something like this. I would like to know how to select max value for each pump.

select a.name, value from out_pumptable as a, (select name, max(value) as value from out_pumptable where group by posnumber)g where and g.value = value 

this code does the job, but i get two entries of Pump 1 since it has two entries with same value.

like image 280
Wai Wong Avatar asked Dec 22 '10 14:12

Wai Wong


People also ask

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 GROUP BY clause?

SQL Server MAX() with GROUP BY clause example First, the GROUP BY clause divided the products into groups by the brand names. Then, the MAX() function is applied to each group to return the highest list price for each brand.

How do you SELECT the maximum value from multiple columns in SQL?

In SQL Server there are several ways to get the MIN or MAX of multiple columns including methods using UNPIVOT, UNION, CASE, etc… However, the simplest method is by using FROM … VALUES i.e. table value constructor. Let's see an example. In this example, there is a table for items with five columns for prices.

How do I SELECT 3 max values in SQL?

To get the maximum value from three different columns, use the GREATEST() function. Insert some records in the table using insert command. Display all records from the table using select statement.


2 Answers

select name, max(value) from out_pumptable group by name 
like image 169
m.edmondson Avatar answered Nov 15 '22 16:11

m.edmondson


SELECT   b.name,   MAX(b.value) as MaxValue,   MAX(b.Anothercolumn) as AnotherColumn FROM out_pumptabl INNER JOIN (SELECT                name,               MAX(value) as MaxValue             FROM out_pumptabl             GROUP BY Name) a ON    a.name = b.name AND a.maxValue = b.value GROUP BY b.Name 

Note this would be far easier if you had a primary key. Here is an Example

SELECT * FROM out_pumptabl c WHERE PK in      (SELECT       MAX(PK) as MaxPK     FROM out_pumptabl b     INNER JOIN (SELECT                    name,                   MAX(value) as MaxValue                 FROM out_pumptabl                 GROUP BY Name) a ON        a.name = b.name AND a.maxValue = b.value)  
like image 20
John Hartsock Avatar answered Nov 15 '22 17:11

John Hartsock