简体   繁体   中英

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
  • Emp ID with single record should come as it is
  • Emp ID with two or more rows:
    • Consider row: having Startdate <= sysdate (the most recent record only)
    • Consider ENDDATE: from rows having ENDATE> sysdate or ENDDATE=null or latest one

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);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM