The cleanest query I could think of at this time is this, if there is no previous contract the query should return NULL
in that field; you can specify a value DEFAULT
for the records not found but it should be of type DATE
but you can also use COALESCE
and% CAST
to change that NULL
to other text if necessary.
SELECT DISTINCT EMPLOYEE_ID, CITY_ID, NOMBRE, APELLIDO,
LAG(CONTRACT_ID, 0 ) OVER (PARTITION BY EMPLOYEE_ID ORDER BY contratos.START_DATE ASC),
LAG(CONTRACT_ID, 1 ) OVER (PARTITION BY EMPLOYEE_ID ORDER BY contratos.START_DATE ASC)
FROM empleados
LEFT JOIN ciudades ON empleados.CITY_ID = ciudades.CITY_ID
LEFT JOIN contratos ON empleados.EMPLOYEE_ID = contratos.EMPLOYEE_ID
ORDER BY contratos.START_DATE
The only drawback is that DISTINCT
must be applied to EMPLOYEE_ID
and therefore the field does not come out in order you can select the correct order if you surround this query with another query:
SELECT CITY_ID, NOMBRE, (orden correcto)... FROM (...TODO EL QUERY ANTERIOR...) alias
I hope I help you.