"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to get the latest value of each group based on timestamp in Oracle SQL?

How to get the latest value of each group based on timestamp in Oracle SQL?

Posted on 2025-04-13
Browse:263

How to Retrieve the Latest Value for Each Group Based on Timestamp in Oracle SQL?

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:

  1. Ranking by Timestamp: Assign a rank to each row within each ID group, ordered by timestamp in descending order.
  2. Selecting Top Ranks: Filter the results to include only the rows with the highest rank for each ID. These rows represent the latest entries.

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:

  • Time-Based Filtering: Add a WHERE clause to the inner query to restrict results to a specific time period.
  • Joining with Other Tables: Integrate data from additional tables by joining on the 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.

Latest tutorial More>

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