fatherazrael
fatherazrael

Reputation: 5977

SQL/Oracle: How to fetch start date row and end date from separate rows for single employee having multiple records in Employee table?

The problem with Employee table is that EMployeeID is coming twice (person id is unique). Creating view which return single data for employee id. Use case:

EMPID     PID     Name    StartDate   End Date .......More Fields

217121  761331  Tefan   21-FEB-19   31-AUG-20
217121  767001  Tefan   01-SEP-20   null
602315  767002  Wolf    01-SEP-20   null
602315  764321  Wolf    01-DEC-15   31-AUG-20
766470  766472  Deva    14-JUL-20   31-DEC-22

Output should be:

217121  761331  Tefan   21-FEB-19   null
602315  764321  Wolf    01-DEC-15   null
766470  766472  Deva    14-JUL-20   31-DEC-22

Using SQL/Oracle.

Current query is taking 9 minutes to fetch 30,000 records. (for 50 records taking 5 to 10 seconds which is a lot); i suggest use some different angle:

select *  from 
(select t1.*,(select t.enddate from (select enddate,empid,
  ROW_NUMBER() OVER (PARTITION BY empid ORDER BY enddate desc) as seqnum
  from employee t2
  where t2.empid=t1.empid) t
   where seqnum=1)  As enddate_1 from (select * from
(select WED.*,ROW_NUMBER() OVER (PARTITION BY empid ORDER BY startdate desc) as seqnum from 
(select t1.*,COUNT(*) OVER (PARTITION BY empid) WDECOUNT from employee t1) WED
where WDECOUNT=1 or WED.startdate <= sysdate)) t1 WHERE seqnum=1);

Upvotes: 0

Views: 1063

Answers (1)

John Mitchell
John Mitchell

Reputation: 472

If this assertion is true;

For each EmployeeId, a later StartDate returns a higher PersonId

Then I can suggest using some MAX/MIN to achieve greater efficiency with your query.

Something like this;

SELECT DISTINCT e.EMPID, MAX(e.PID), e.Name, MIN(e.startdate), 
MAX(e.enddate) keep (dense_rank first order by enddate desc nulls first)
FROM employee e
WHERE e.startdate <= SYSDATE
GROUP BY e.EMPID, e.Name;

Edit; include WHERE startdate < sysdate

Upvotes: 1

Related Questions