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

时间:2013-07-23 15:47:14

标签: sql sql-server-2008 greatest-n-per-group

我目前有下表:

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

我需要的是state来自上一个userid的每个不同的eventtime,类似于以下内容:

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

4 个答案:

答案 0 :(得分:11)

SELECT
ID, Name, EventTime, State
FROM
MyTable mt
WHERE EventTime = (SELECT MAX(EventTime) FROM MyTable sq WHERE mt.ID = sq.ID)

答案 1 :(得分:7)

在支持分析功能的数据库中,您可以使用row_number()

select  *
from    (
        select  row_number() over (partition by ID 
                                   order by EventTime desc) as rn
        ,       *
        from    YourTable
        ) as SubQueryAlias
where   rn = 1

答案 2 :(得分:2)

您没有指定正在使用的数据库,但您应该能够在子查询中使用聚合函数来获取每个ID的最大事件时间:

select t1.id,
  t1.name,
  t1.eventtime,
  t1.state
from mytable t1
inner join
(
  select max(eventtime) eventtime, id
  from mytable
  group by id
) t2
  on t1.id = t2.id
  and t1.eventtime = t2.eventtime
order by t1.id;

请参阅SQL Fiddle with Demo

答案 3 :(得分:2)

你可以试试这个: -

SELECT ID, Name, EventTime, State
FROM mytable mm Where EventTime IN (Select MAX(EventTime) from mytable mt where mt.id=mm.id)

<强> SQL FIDDLE