Select distinct rows whilst grouping by max value

时光毁灭记忆、已成空白 提交于 2019-12-01 04:02:55

In databases that support analytic functions, you could use 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
ID, Name, EventTime, State
FROM
MyTable mt
WHERE EventTime = (SELECT MAX(EventTime) FROM MyTable sq WHERE mt.ID = sq.ID)

You did not specify what database you are using but you should be able to use an aggregate function in a subquery to get the max event time for each 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;

See SQL Fiddle with Demo

You can try this:-

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

SQL FIDDLE

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!