简体   繁体   中英

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.

What about

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

See:

它并不像你想象的那么难。

select name, date, max(number) from table group by name, date
SELECT Name, Date, MAX(Number)
    FROM YourTable
    GROUP BY Name, Date;
SELECT Name, `Date`, MAX(Number)
FROM yourtable
GROUP BY Name, `Date`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM