I have two tables emp_master and transfer. for each employee_id
in emp_master there can be multiple entries in transfer table. I want to get the latest
record from the transfer table based on date_of_tansfer and display it with data from
emp_master. I have written a query like this which is not working. I am getting a error
“EMP.EMPLOYEE_ID: invalid identifier”. I can get the details for single employee if i hardcode
it with that employee_id.. but how can i modify it to get data for all the employees..
select distinct emp.employee_id,trnsf.OU
from emp_master emp
left join (select * from (select * from transfer where employee_id = emp.employee_id
and date_of_transfer <= SYSDATE order by date_of_transfer desc) where rownum = 1) trnsfr
on trnsfr.EMPLOYEE_ID = emp.employee_id
CREATE TABLE "EMP_MASTER"
( "EMPLOYEE_ID" NUMBER(10,0),
"FIRST_NAME" VARCHAR2(30 BYTE),
"MIDDLE_NAME" VARCHAR2(30 BYTE),
"SURNAME" VARCHAR2(30 BYTE),
)
CREATE TABLE "TRANSFER"
( "EMPLOYEE_SR_NO" NUMBER,
"EMPLOYEE_ID" NUMBER(10,0),
"DATE_OF_TRANSFER" DATE,
"OU" VARCHAR2(30 BYTE)
)
The reason you are getting that error is the nesting level of your derived tables (sub-queries). A sub-query can “see” only the columns/tables from the immediate “parent” query (which in your case is the outer select that limits the result to one row).
The following should do what you want:
If
date_of_transferis really a “DATE” (i.e. no time involved) than you might consider usingdate_of_transfer <= trunc(SYSDATE)instead in order to “remove” the time from the SYSDATE result.