Need To Pull Most Recent Record By Timestamp Per Unique ID

≡放荡痞女 提交于 2019-12-06 15:04:32

If the Unique ID is truely unique, then you will always have the most recent latitude and longitude, because the ID will change with every singe row.

If the Unique ID is a Foreign Key (or an ID referencing a unique ID from a different table) you should do something like this:

SELECT latitude, longitude, unique_id
FROM table INNER JOIN
(SELECT unique_id, MAX(timestamp) AS timestamp
FROM table
GROUP BY unique_id)t2 ON table.timestamp = t2.timestamp
AND table.unique_id = t2.unique_id;

You can use the row_number() function for this purpose:

select id, latitude, longitude, timestamp, . . .
from (select t.*,
             row_number() over (partition by id order by timestamp desc) as seqnum
      from t
     ) t
where seqnum = 1

The row_number() function assigns a sequential value to each id (partition by clause), with the most recent time stamp getting the value of 1 (the order by clause). The outer where just chooses this one value.

This is an example of a window function, which I encourage you to learn more about.

One quibble with your question: you describe the id as unique. However, if there are multiple values at different times, then it is not unique.

Check this link to implement row indexes and utilize the partition to reset per group. Then in your WHERE clause filter out the results that aren't the first.

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