Skip to content
Advertisement

Query that returns date of first and last record for each day within a d

I have a table that records vehicle locations and I wish to query this to get the first and the last record for each vehicle for each day in a date range. The table looks like:

There are multiple vehicles with three weeks worth of data being held in the table 100,000 records this is written to an archive every night which leaves a 21 days of records which I wish to query. With my sample I would like to get:

I have an existing query that gets the most recent records but this can’t be used for my requirements as it uses the MAX(ID) within the query and I don’t believe that you can mix both MAX and MIN in the same query. I could use this as the basis of a table in a stored procedure and then loop through the records and query each to get the first record in the date range but this would be a very resource greedy process! I have included this purely to show what I already have:

Advertisement

Answer

You can mix Max and Min in the same query.

Here is DBFiddle demo.

EDIT: If there could be entries for the same registration at the same time (ID is unique and increasing – ordered by dateOfRecord):

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement