SELECT s.EmployeeID,e.LastName,projectID,sum(s.HoursWorked) AS Total_Hours
from TimeSheet s
full join Employee e ON e.EmployeeID = s.EmployeeID
full Join Project p
ON p.ProjectID = e.EmployeeID
group by p.ProjectID,s.EmployeeID,e.LastName
显示这个
Employeid Lastname projectID Sum(hoursWorked)
4 Peacock NULL 33.00
5 Buchanan NULL 44.00
1 Davolio 1 56.00
2 Fuller 2 41.00
3 Leverling 3 42.00
我希望项目 ID 显示为 2 个 NULLS。
更新:这几乎是我需要的。
SELECT COALESCE(et.EmployeeID, p.projectID) AS employeeID
, e.LastName
, COALESCE(p.projectID, et.EmployeeID) AS projectID
, sum(s.HoursWorked) AS Total_Hours
from TimeSheet s
inner join Employee e ON e.EmployeeID = s.EmployeeID
inner join EmployeeTask et on e.EmployeeID = et.EmployeeID
inner join Task t On t.TaskID=et.TaskID
inner join Project p on p.ProjectID=t.ProjectID
group by p.ProjectID, et.EmployeeID, e.LastName
这产生
Employeid Lastname projectID Sum(hoursWorked)
1 Davolio 1 112.00
2 Fuller 1 82.00
3 Leverling 2 84.00
4 Peacock 2 66.00
5 Buchanan 3 88.00
WHIch 将我带到此链接Using multiple JOINS。SUM() 产生错误的值
更新答案:然后我重写了我的 sql 以获得正确的答案。
SELECT COALESCE(et.EmployeeID, p.projectID) AS employeeID
, COALESCE(p.projectID, et.EmployeeID) AS projectID
, e.LastName
, (Select sum(HoursWorked)
FROm TimeSheet
WHere TimeSheet.EmployeeID=e.EmployeeID
)AS Total_Hours
from TimeSheet s
inner join Employee e ON e.EmployeeID = s.EmployeeID
inner join EmployeeTask et on e.EmployeeID = et.EmployeeID
inner join Task t On t.TaskID=et.TaskID
inner join Project p on p.ProjectID=t.ProjectID
group by p.ProjectID, et.EmployeeID, s.EmployeeID,e.EmployeeID, e.LastName