I have a table with three columns: id (NUMBER), data_dt (DATE), and data_value (NUMBER).
There is a primary key on id and data_dt.
I want to select the record with the latest data_dt for each unique id.
What is the best way to do this?
I have three different methods, but there may be something I am missing.
First:
SELECT *
FROM
(
SELECT id, data_dt, data_value,
FIRST_VALUE(data_dt)
OVER (PARTITION BY id ORDER BY data_dt DESC) AS last_data_dt
FROM the_table
)
WHERE data_dt = last_data_dt;
(I use ORDER BY...DESC instead of just ORDER BY so I don't need the ROWS BETWEEN clause)
Second:
SELECT t1.*
FROM the_table t1
JOIN
(
SELECT id, MAX(data_dt) AS last_data_dt
FROM the_table
GROUP BY id
) t2 ON (t2.id = t1.id AND t2.data_dt = t1.data_dt);
Third:
SELECT t1.*
FROM the_table t1
WHERE t1.data_dt =
(
SELECT MAX(t2.data_dt)
FROM the_table t2
WHERE t2.id = t1.id
);
-- Don