Search code examples
sqloracle-databasegroup-byunique

How to select unique records when duplicates exist


I am trying to write a query that will show only the latest HEAR_DT for each APEL_ID

SELECT APEL_ID, HEAR_DT 
FROM HEARINGS
APEL_ID HEAR_DT
101 01-OCT-08
101 02-OCT-08
101 03-OCT-08
102 06-OCT-08
102 07-OCT-08
102 08-OCT-08
103 09-OCT-08
103 10-OCT-08
103 11-OCT-08
104 23-OCT-08
104 24-OCT-08
104 25-OCT-08
104 25-OCT-08

When I write the query as usual, I get the unique records to an extent, but the records where the HEAR_DT are identical are both showing up

The HEAR_DT is a "date" and not a "datetime" data type so I have no way of using the time component to select the Max

Is there anything that can be done to this query (or a different query written), that can show only unique records. I will like to show any of the ones that are showing as duplicates. It does not matter which of them get picked. (something like "Top 1" or "Any")

SELECT APEL_ID, MAX(HEAR_DT) AS LATEST_HEAR_DT 
FROM HEARINGS 
GROUP BY APEL_ID
APEL_ID LATEST_HEAR_DT
101 03-OCT-08
102 08-OCT-08
103 11-OCT-08
104 25-OCT-08
104 25-OCT-08

Solution

  • Here is the solution. This works

    SELECT UNIQUE APEL_ID, MAX(TO_DATE(HEAR_DT, 'DD-MON-YY')) AS LATEST_HEAR_DT 
    FROM mytable  
    GROUP BY APEL_ID