sql – 按最大值分组时选择不同的行

我目前有下表:
ID   |  Name    |  EventTime            |  State
1001 |  User 1  |  2013/07/22 00:00:05  |  15
1002 |  User 2  |  2013/07/23 00:10:00  |  100
1003 |  User 3  |  2013/07/23 06:15:31  |  35
1001 |  User 1  |  2013/07/23 07:13:00  |  21
1001 |  User 1  |  2013/07/23 08:15:00  |  25
1003 |  User 3  |  2013/07/23 10:00:00  |  22
1002 |  User 2  |  2013/07/23 09:18:21  |  50

我需要的是上次事件时间中每个不同用户标识的状态,类似于以下内容

ID   |  Name    |  EventTime            |  State
1001 |  User 1  |  2013/07/23 08:15:00  |  25
1003 |  User 3  |  2013/07/23 10:00:00  |  22
1002 |  User 2  |  2013/07/23 09:18:21  |  50

我需要类似下面的东西,但我不能得到我需要的东西.

SELECT ID,Name,max(EventTime),State
FROM MyTable
GROUP BY ID

解决方法

支持分析函数数据库中,您可以使用row_number():
select  *
from    (
        select  row_number() over (partition by ID 
                                   order by EventTime desc) as rn,*
        from    YourTable
        ) as SubQueryAlias
where   rn = 1

相关文章

SELECT a.*,b.dp_name,c.pa_name,fm_name=(CASE WHEN a.fm_n...
if not exists(select name from syscolumns where name=&am...
select a.*,pano=a.pa_no,b.pa_name,f.dp_name,e.fw_state_n...
要在 SQL Server 2019 中设置定时自动重启,可以使用 Window...
您收到的错误消息表明数据库 'EastRiver' 的...
首先我需要查询出需要使用SQL Server Profiler跟踪的数据库标...