简体   繁体   中英

SQL: Select a row only if that cell has the max value given the ID

I realize the title of the question is much more difficult than the question itself.

Basically I have a dataset like this one:

ID  Hour
01  1
01  2
01  3
02  1
02  2
03  1
03  2
03  3
03  4

The dataset refers to people that are playing a game. ID is, of course, the ID of the subject whilst 'Hour' refers to what happened in that hour of game. Now, I would like to select only the rows that refer to the last hour played by that player .

So that:

ID  Hour
01  3
02  2
03  4

Any ideas?

simply use MAX()

SELECT ID, MAX(HOUR) Max_hour
FROM   TableName
GROUP  BY ID

here is the solution

SELECT ID, MAX(HOUR) as Maxhour FROM Table1 GROUP BY ID

In the event that you actually want to select other columns on the same row, then the simple group by / max solution doesn't quite work.

One solution that works in any database that supports window functions is:

select t.*
from (select t.*,
             row_number() over (partition by id order by hour desc) as seqnum
      from TableName t
     ) t
where seqnum = 1

OR, if you want to make it more complicated as it is^^ this is the way to go:

select * from tablename t1 where t.hour = (select max(hour) from tablename t2 where t2.id = t1.id)

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