Need To Pull Most Recent Record By Timestamp Per U

2019-05-19 01:11发布

问题:

I'm going to apologize up front, this is my first question on stackoverflow...

I am attempting to query a table of records where each row has a VehicleID, latitude, longitude, timestamp and various other fields. What I need is to only pull the most recent latitude and longitude for each VehicleID.

edit: removed the term unique ID as apparently I was using it incorrectly.

回答1:

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;


回答2:

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.



回答3:

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.