Skip to Main Content

SQL & PL/SQL

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Best way to select distinct values based on another column?

DonbotOct 19 2009 — edited Oct 19 2009
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
This post has been answered by Centinul on Oct 19 2009
Jump to Answer
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Nov 16 2009
Added on Oct 19 2009
6 comments
1,117 views