I have the following tables:
EMPLOYEE
ID |NOMBRE | APELLIDO
1 |TEST | TEST
2 |TEST2 | TEST2
3 |TEST3 | TEST3
4 |TEST4 | TEST4
DIRECTION
ID | DIRECCION | EMP_ID | PAIS_ID |FECHA_INSERCION
1 | DIR1 | 1 | 1 |10/10/2019 08:00:00
2 | DIR2 | 1 | 1 |10/10/2019 08:15:00
3 | DIR3 | 1 | 5 |10/10/2019 08:20:00
I want to get the last registered address of the employee
for instance
TEST | TEST | DIR1 | 5 | 10/10/2019 08:20:00
I have tried the following query
Select Nombre,Apellido, Pais_ID, DIRECCION, MAX(FECHA_INSERCION)
FROM EMPLEADO EMP
INNER JOIN DIRECCION DIR ON EMP.ID = DIR.EMP_ID
GROUP BY Nombre, Apellido, Pais_ID, DIRECCION
However this gets me the following:
TEST | TEST | DIR1 | 1 | 10/10/2019 08:15:00
TEST | TEST | DIR1 | 5 | 10/10/2019 08:20:00
How could I fix the query to get what I need?
It is not entirely clear to me if you are looking for a particular case or the last addresses of all employees, if it is the latter, you can pivot with a subquery that gives you the last date for each employee:
You incorporate this into your own query to filter only the rows where
FECHA_INSERCION = ULTIMA_FECHA_INSERCION
. Something like that:On the contrary, if you are looking for a single case, the natural way would be to sort by
FECHA_INSERCION
descending and keep the first of the rows. Unfortunately, Oracle in versions prior to 12c does not have a row limitation clause like other managers, so the trick is to materialize a row number according to the order in a subquery and filter the firstAnother similar way to the previous one is to use the function
ROW_NUMBER()
to numberTo generate the row number, the advantage is that you generate a unique numerator for each employee, so ultimately, you could solve the query for everyone, using the same filter:
WHERE T.RN = 1
Grades:
rownum
is resolved after theorder
after thewhere
therefore it is necessary to use a subquery to materialize this row numberYou would need to add a
TOP 1
so that it returns only one value (in Oracle it is withrownum
) and also add aORDER BY
so that it orders them from highest to lowest date, that way the top 1 will always be theFECHA_INSERCIÓN
highest: