I need to extract one record from column Y where in column date has the last date
example
id | Y | DATE |
---|---|---|
a | 1 | 2020 |
a | 2 | 2021 |
a | 2 | 2022 |
b | 1 | 1999 |
b | 1 | 2015 |
c | 3 | 2001 |
c | 3 | 2004 |
c | 7 | 2010 |
I need to extract one record from column Y where in column date has the last date
example
id | Y | DATE |
---|---|---|
a | 1 | 2020 |
a | 2 | 2021 |
a | 2 | 2022 |
b | 1 | 1999 |
b | 1 | 2015 |
c | 3 | 2001 |
c | 3 | 2004 |
c | 7 | 2010 |
One option is to rank rows per each id sorted by years in descending order, and then fetch the ones that ranked as the highest.
Sample data:
SQL> with
2 test (id, y, datum) as
3 (select 'a', 1, 2020 from dual union all
4 select 'a', 2, 2021 from dual union all
5 select 'a', 2, 2022 from dual union all
6 select 'b', 1, 1999 from dual union all
7 select 'b', 1, 2015 from dual union all
8 select 'c', 3, 2001 from dual union all
9 select 'c', 3, 2004 from dual union all
10 select 'c', 7, 2010 from dual
11 ),
Query:
12 temp as
13 (select id, y, datum,
14 rank() over (partition by id order by datum desc) rnk
15 from test
16 )
17 select id, y, datum
18 from temp
19 where rnk = 1;
ID Y DATUM
-- ---------- ----------
a 2 2022
b 1 2015
c 7 2010
SQL>