2013-07-23 64 views
7

目前,我有如下表:同时通过最大值分组选择不同的行

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 
+0

可能重复[SQL服务器采用最新的值选择不同的行只(http://stackoverflow.com/questions/ 3442931/sql-server-select-distinct-rows-using-most-recent-value-only) – Bulat

回答

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 
11
SELECT 
ID, Name, EventTime, State 
FROM 
MyTable mt 
WHERE EventTime = (SELECT MAX(EventTime) FROM MyTable sq WHERE mt.ID = sq.ID) 
+1

虽然我更喜欢'row_number()',这可能会在某些情况下表现最好。 –

+0

这也是标准的SQL :) Row_number()在任何地方都不可用。 – fancyPants

+2

。 。 'row_number()'*是* ANSI标准SQL。问题是,没有真正的数据库真正实现该标准。 –

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

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

+0

这并不涉及MAX(EventTime)与ID,它仅限于任何ID的MAX()的事件时间,如果一个ID的非最大事件时间碰巧是另一个ID的最大事件时间,则会失败ID。 –

+0

@Goat CO你是绝对正确的兄弟。我得到了你所说的。我已经更新了它,现在工作正常。 :) –

+0

是的,修复它,它现在是一个相关的子查询,所以它正在评估每个ID的最大值。它可以很容易地用'='而不是'IN',因为子查询为每个ID返回一个值。 –

相关问题