简体   繁体   中英

Write a Query to find the last day of first job of every employee

Write a Query to find the last day of first job of every employee.

Using HR Schema

TABLE - job_history 
employee_id  
start_date 
end_date`   
job_id      
department_id

i have tried this.This will work assuming dates don't overlap Please suggest any other way.

select  employee_id, min(end_date)
from job_history
group by employee_id;

Your query is OK if the job dates never overlap.

If they do, then the following MySQL 8.x query will do:

select 
  employee_id,
  end_date
from (
  select
    employee_id,
    start_date,
    end_date,
    row_number() over(partition by employee_id order by start_date) as rn  
  from job_history
) x
where rn = 1

With NOT EXISTS :

select j.employee_id, j.end_date 
from job_history j
where not exists (
  select 1 from job_history
  where employee_id = j.employee_id and start_date < j.start_date
)

or:

select j.employee_id, j.end_date 
from job_history j
where j.start_date = (
  select min(start_date) 
  from job_history
  where employee_id = j.employee_id
)

If there is a case that an employee started first at the same day 2 different jobs, then these queries will return both end dates since there is no column to distinguish between the 2. But you could get the min end date between them, with

select j.employee_id, min(j.end_date)

and add:

group by j.employee_id 

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