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.
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.
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:
You can use the
row_number()
function for this purpose:The
row_number()
function assigns a sequential value to each id (partition by
clause), with the most recent time stamp getting the value of1
(theorder by
clause). The outerwhere
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.