Retrieve the latest value of each group based on time
Question:
Consider the following Oracle table:
<code>id date quantity 1 2010-01-04 11:00 152 2 2010-01-04 11:00 210 1 2010-01-04 10:45 132 2 2010-01-04 10:45 318 4 2010-01-04 10:45 122 1 2010-01-04 10:30 1 3 2010-01-04 10:30 214 2 2010-01-04 10:30 5515 4 2010-01-04 10:30 210</code>
The goal is to retrieve the latest value (and its timestamp) by id group. Expected output should be:
<code>id date quantity 1 2010-01-04 11:00 152 2 2010-01-04 11:00 210 3 2010-01-04 10:30 214 4 2010-01-04 10:45 122</code>
Solution:
To do this, create an inline view that ranks each row in the id group based on descending timestamp:
SELECT RANK() OVER (PARTITION BY id ORDER BY ts DESC) AS rnk, id, ts, qty FROM qtys
Then filter the record with rank 1 to get the latest value:
SELECT x.id, x.ts AS "DATE", x.qty AS "QUANTITY" FROM (SELECT * FROM qtys) x WHERE x.rnk = 1
Advanced options:
WHERE x.ts >= sysdate - INTERVAL 'XX' MINUTE
SELECT x.id || '-' || y.idname AS "ID", x.ts AS "DATE", x.qty AS "QUANTITY" FROM (SELECT * FROM qtys) x LEFT JOIN another_table y ON x.id = y.id
The above is the detailed content of How to Retrieve the Latest Value for Each Group Based on Timestamp in Oracle?. For more information, please follow other related articles on the PHP Chinese website!