Consider the following schema of a company database (primary keys are in bold).
Employee (**EmployeeID**, Name, Office, Email, Sex, Salary, DepartmentID)
Department (**DepartmentID**, DepartmentName)
Project (**ProjectID**, DepartmentID, Duration)
EmployeeProject (**EmployeeID, ProjectID**, WorkHours)
Find the proejct whose total work hours is the second longest, with SINGLE QUERY statement. Try not use top or limit.
Below is my solution, its rather ugly and inefficient.
select projectid
from (
select projectid, sum(workhours) as hours
from employeeproject ep
group by projectid
) sum
where hours = (
select max(hours)
from (
select projectid, hours
from (
select projectid, sum(workhours) as hours
from employeeproject ep
group by projectid
) sum
where hours < (
select max(hours)
from (
select projectid, sum(workhours) as hours
from employeeproject ep
group by projectid
) sum
)
) sec
)