Extracting the Most Recent Entries for Each Group in Oracle SQL
This tutorial demonstrates a common database task: retrieving the most recent record for each group based on a timestamp. We'll use a table containing IDs, timestamps, and quantities as an example.
Challenge:
Given a table with ID, timestamp ("date"), and quantity ("quantity") columns, how do we efficiently select the latest quantity (and its associated timestamp) for every unique ID?
Solution:
This can be achieved using the following approach:
The following Oracle SQL query implements this solution:
SELECT x.id, x."date", x.quantity
FROM (
SELECT
id,
"date",
RANK() OVER (PARTITION BY id ORDER BY "date" DESC) AS rnk,
quantity
FROM qtys
) x
WHERE x.rnk = 1;
Extending the Query:
This basic query can be adapted to meet more complex needs:
WHERE
clause to the inner query to restrict results to a specific time period.id
column. For instance, you could join to a table containing ID and name to include names in the output.This method provides a robust and efficient way to retrieve the latest values per group based on a timestamp in Oracle SQL, applicable to various data analysis and manipulation tasks.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3