SQL Exercise: The date when he left his last job and his employee ID
SQL SORTING and FILTERING on HR Database: Exercise-32 with Solution
32. From the following table, write a SQL query to find those employees who have completed their previous jobs. Return employee ID, end_date.
Sample table : job_history+-------------+------------+------------+------------+---------------+ | EMPLOYEE_ID | START_DATE | END_DATE | JOB_ID | DEPARTMENT_ID | +-------------+------------+------------+------------+---------------+ | 102 | 2001-01-13 | 2006-07-24 | IT_PROG | 60 | | 101 | 1997-09-21 | 2001-10-27 | AC_ACCOUNT | 110 | | 101 | 2001-10-28 | 2005-03-15 | AC_MGR | 110 | | 201 | 2004-02-17 | 2007-12-19 | MK_REP | 20 | | 114 | 2006-03-24 | 2007-12-31 | ST_CLERK | 50 | | 122 | 2007-01-01 | 2007-12-31 | ST_CLERK | 50 | | 200 | 1995-09-17 | 2001-06-17 | AD_ASST | 90 | | 176 | 2006-03-24 | 2006-12-31 | SA_REP | 80 | | 176 | 2007-01-01 | 2007-12-31 | SA_MAN | 80 | | 200 | 2002-07-01 | 2006-12-31 | AC_ACCOUNT | 90 | +-------------+------------+------------+------------+---------------+
Sample Solution:
-- Selecting 'employee_id' and the maximum 'end_date'
SELECT employee_id, MAX(end_date)
-- Specifying the table to retrieve data from ('job_history')
FROM job_history
-- Filtering the results to include only those 'employee_id' values that appear more than once
WHERE employee_id IN (
-- Subquery: Selecting 'employee_id' from 'job_history', grouping by 'employee_id', and filtering the count to be greater than 1
SELECT employee_id
FROM job_history
GROUP BY 1
HAVING COUNT(employee_id) > 1
)
-- Grouping the results by 'employee_id'
GROUP BY 1;
Sample Output:
employee_id | max -------------+------------ 101 | 2005-03-15 200 | 2006-12-31 176 | 2007-12-31 (7 rows)
Code Explanation:
The said query in SQL that retrieves the employee ID and the latest end date for each employee with multiple job history entries. The query first selects the employee IDs that have more than one entry in the 'job_history' table using a subquery and the "HAVING COUNT" clause. Then, it retrieves the employee IDs and their corresponding maximum end dates from the 'job_history' table, grouping the results by the employee IDs.
Practice Online
Query Visualization:
Duration:
Rows:
Cost:
Contribute your code and comments through Disqus.
Previous SQL Exercise: Departments more than 10 employees who get commissions.
Next SQL Exercise: A department 50 employee without a commission %.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/sql-exercises/sorting-and-filtering-hr/sql-sorting-and-filtering-hr-exercise-32.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics