使用SELECT MAX()和GROUP BY时如何包含主键?

时间:2016-03-08 14:15:07

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

鉴于下表:

TrackID  IMEI             LastPacketTime
45       862950022901642  2015-09-23 18:25:16.000
62       862950022901642  2015-09-24 06:50:16.000
99       862950022901642  2015-09-25 22:27:49.000

..当我想为每个IMEI选择最近一行时,如何返回TrackID?如果我按IMEI分组,我将失去包含TrackID的能力。

我当前的SQL如下(但不包括我需要的TrackID):

SELECT IMEI, MAX(LastPacketTime) AS LastPacketTime
FROM dbo.Tracks  
GROUP BY IMEI

2 个答案:

答案 0 :(得分:2)

您可以使用ROW_NUMBER

SELECT TrackID,  IMEI, LastDate
FROM (
  SELECT TrackID,  IMEI, LastDate, 
         ROW_NUMBER() OVER (PARTITION BY IMEI 
                            ORDER BY LastPacketTime DESC) AS rn
  FROM dbo.Tracks) AS t
WHERE t.rn = 1

如果您有多个记录共享相同的最大LastPacketTime值,并且您希望返回所有这些记录的TrackID值,请使用RANK代替ROW_NUMBER

修改:如果有关联,您可以延长ORDER BY的{​​{1}}条款,以便有选择地选择较小的ROW_NUMBER

TrackID

或更大的一个:

ORDER BY LastPacketTime DESC, TrackID

答案 1 :(得分:0)

这是一个通用查询,但如果同时出现多次,则会产生最大trackid

select max(t1.trackid) as trackid,
    t1.imei,max(t1.lastdate)
from 
tracks t1 
    inner join 
tracks t2
    on t1.imei=t2.imei
where t1.lastdate > t2.lastdate
group by t1.imei,t1.lastdate