Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL: How to select a max value for each group per day?

Let's say I have a table that has the following columns...

Name, Date, Number

And say we had the following data inserted into these columns...

Bob, 2011-11-22, 1
Bob, 2011-11-22, 5
Bob, 2011-11-22, 4
Bob, 2011-11-22, 3
Wendy, 2011-11-22, 3
Wendy, 2011-11-22, 4
Wendy, 2011-11-22, 2
Wendy, 2011-11-22, 1
Chris, 2011-11-22, 4
Chris, 2011-11-22, 1
Bob, 2011-11-21, 4
Bob, 2011-11-21, 3
Wendy, 2011-11-21, 2
Wendy, 2011-11-21, 4
Wendy, 2011-11-21, 1
Chris, 2011-11-21, 4
Chris, 2011-11-21, 1

Now what I'd like to do is get the max Number value for each Name, for each date. So my query result would look like this...

Bob, 2011-11-22, 5
Wendy, 2011-11-22, 4
Chris, 2011-11-22, 4
Bob, 2011-11-21, 4
Wendy, 2011-11-21, 4
Chris, 2011-11-21, 4

Any help would be appreciated. I'm using SQL 2005.

like image 359
mike Avatar asked Nov 22 '11 16:11

mike


People also ask

How do you SELECT maximum value of each group in SQL?

How do you get max for each group in SQL? To find the maximum value of a column, use the MAX() aggregate function; it takes a column name or an expression to find the maximum value. In our example, the subquery returns the highest number in the column grade (subquery: SELECT MAX(grade) FROM student ).

Can we use max with GROUP BY in SQL?

The GROUP BY statement is often used with aggregate functions ( COUNT() , MAX() , MIN() , SUM() , AVG() ) to group the result-set by one or more columns.

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

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,...) Given two or more arguments, it returns the largest (maximum-valued) argument.

How do you find the maximum occurrence of a value in SQL?

To find the max value of a column, use the MAX() aggregate function; it takes as its argument the name of the column for which you want to find the maximum value. If you have not specified any other columns in the SELECT clause, the maximum will be calculated for all records in the table.


2 Answers

What about

SELECT [Name], [Date], MAX(Number)
FROM [yourTable]
GROUP BY [Name], [Date] 

See:

  • GROUP BY (Aggregate) Functions
  • MySQL GROUP BY - Aggregate Functions
like image 199
Code Magician Avatar answered Oct 07 '22 13:10

Code Magician


It's not as hard as you'd think.

select name, date, max(number) from table group by name, date
like image 23
flesk Avatar answered Oct 07 '22 11:10

flesk