SQL >> Base de Datos >  >> RDS >> Oracle

Dos formas de obtener la fila con la fecha más reciente

El enfoque clásico consiste en una subconsulta que calcula max(process_date) y luego se une a ella:

select c1.b_id, c2.MaxDate from table_a a inner join table_b b on a.a_id = b.a_id inner join table_c c1 on b.b_id = c1.b_id inner join ( select max(process_date) MaxDate from table_c ) c2 on c1.process_date = c2.maxdate; 

Prueba de ejemplo: SQL Fiddle con demo

La alternativa es usar una función analítica que asigne un orden:

select b_id, process_date from ( select c1.b_id, c1.process_date, row_number() over(partition by a.a_id order by c1.process_date desc) rn from table_a a inner join table_b b on a.a_id = b.a_id inner join table_c c1 on b.b_id = c1.b_id ) where rn = 1 

Prueba de ejemplo: SQL Fiddle con demo

Si necesitas la fila más reciente por cada cuenta y no una única fila global, quédate con la segunda variante.