Question

I've been really stumped at trying to crack this problem. I'm trying to find the employee who has the most sick leave by each department. If the're still a current employee they have no end date. I've tried tweaking this every way I can but I keep getting multiple results. I only want the employee who has the most hours within each department.

Select H.DepartmentID, max(E.SickLeaveHours) as MaxSick, E.EmployeeID
From HR.Department as D,
     HR.EmployeeDepartmentHistory as H,
     HR.Employee as E
Where E.EmployeeID = H.EmployeeID
and D.DepartmentID = H.DepartmentID
and H.EndDate is null
group by H.DepartmentID, E.EmployeeID

DepartmentID   MaxHours        EmployeeID
7              61              8
1              22              9
7              64              10
1              23              11
1              20              12
Was it helpful?

Solution

select temp.DepartmentID, temp.SickLeaveHours as MaxSick, EH.EmployeeID from
(Select H.DepartmentID DepartmentID, max(E.SickLeaveHours) SickLeaveHours
From HR.Department D,
HR.EmployeeDepartmentHistory H,
HR.Employee E
Where E.EmployeeID = H.EmployeeID
and D.DepartmentID = H.DepartmentID
and H.EndDate is null
group by H.DepartmentID) temp, HR.EmployeeDepartmentHistory EH, Employee emp
Where EH.DepartmentID = temp.DepartmentID
and emp.SickLeaveHours = temp.SickLeaveHours
and emp.employeeId = EH.employeeId

The first step of the solution is to find maximum sick leaves per department. This is answered by the inner query above.

The next step is to find the employees for that department matching that maximum number of hours, which is answered by the joins in the outer query.

If more than one employees have same maximum sick leave hours, then the query will return all such employees for the department.

Don't know if this is relevant here or not, but it looks like to me that sick leave hours are somehow cumulative hours for an employee irrespective of the department he/she has worked in since the sick leave hours are "attribute" of "Employee" and not "EmployeeDepartmentHistory". So, the sick leave hours may been consumed/earned in a previous department, but would appear in current department (where enddate is null in EmployeeDepartmentHistory) for this query.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top