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.
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 ).
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.
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.
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.
What about
SELECT [Name], [Date], MAX(Number)
FROM [yourTable]
GROUP BY [Name], [Date]
See:
It's not as hard as you'd think.
select name, date, max(number) from table group by name, date
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