通过deviceid从每个组中获取最新的1条记录

时间:2019-12-10 09:00:47

标签: sql-server group-by

如何从每台设备获取最新记录?

查询尝试

select * from Data 
where dname = 'abc'
group by did
order by timestamp desc

样本数据

sl  emei            mname dname did timestamp
66  868997036667    LB    abc   52  59.6 2019-09-06 14:51:21.0000000
67  868997036667    LB    abc   46  59.3 2019-09-06 15:51:21.0000000
68  868997036667    LB    abc   52  58.4 2019-09-06 16:51:21.0000000
69  868997036667    LB    abc   46  58.5 2019-09-06 17:51:21.0000000

预期产量

68  868997036667    LB    abc   52  58.4 2019-09-06 16:51:21.0000000
69  868997036667    LB    abc   46  58.5 2019-09-06 17:51:21.0000000

1 个答案:

答案 0 :(得分:0)

您可以将row_number()partition一起使用。

select * 
from (select sl, emei, mname, dname, timestamp, did
    , row_number() over (partition by did order by sl desc) as rn
    from Data where dname = 'abc') t1 
where t1.rn = 1