Suppose I have queried a table called items_run to get the following results:
object_id item_id run_date
0 1010 8/1/2023
1 1020 8/3/2023
2 1030 8/4/2023
3 1010 8/5/2023
4 1020 8/6/2023
Here’s the query:
SELECT object_id,
item_id,
run_date
FROM items_run
WHERE run_date > '2023-07-30'
I want to adjust my query to select the rows with only the most recent run_date for a particular item_id. So it would look like this:
object_id item_id run_date
0 1010 8/5/2023
1 1020 8/6/2023
2 1030 8/4/2023
I have tried to add WHERE run_date > '2023-07-30' AND run_date = (SELECT MAX(run_date) FROM items_run)
, but that just returned an empty table. How could I accomplish my goal here?
2
Answers
As one option, you can get the max
run_date
for eachitem_id
into a result set:Then you can use that as a subquery in a join:
A simple aggregate gives you exactly what you’re asking for: