Reputation: 63
This is what the current table looks like.
item | description | date |
---|---|---|
12-001 | SIM CARD | 04/06/2021 |
12-001 | SIM CARD-1 | 04/07/2021 |
I want to get the latest distinct item from the above table. The record that I am trying to get will look like this since this record has the latest date.
item | description | date |
---|---|---|
12-001 | SIM CARD-1 | 04/07/2021 |
I'm using Oracle. Below is my query. Any help is appreciated.
SELECT DISTINCT item , description, date FROM items
Upvotes: 0
Views: 59
Reputation: 50017
On recent (12.x and greater) versions of Oracle you can use something like:
SELECT *
FROM ITEMS
ORDER BY "date" DESC
FETCH FIRST 1 ROWS ONLY
Note that "date"
is quoted in this query because date
is not a valid identifier in Oracle unless quoted, as it's also the name of a data type, the ANSI date specifier, and probably some other things I've forgotten.
Upvotes: 0
Reputation: 13509
Since your description column has different data so DISTINCT keyword would not work here. You may try below query with window function -
SELECT item , description, date
FROM (SELECT item, description, date, ROW_NUMBER() OVER(PARTITION BY item ORDER BY date DESC) RN
FROM items)
WHERE RN = 1;
Upvotes: 0
Reputation: 48750
You can use ROW_NUMBER()
to identify the rows you want.
For example:
select item, description, date
from (
select i.*,
row_number() over(partition by item order by date desc) as rn
from items i
) x
where rn = 1
In this case only the last row for every item will have the row number as 1.
Upvotes: 1