0
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
4

3 回答 3

3

你可以使用这个查询:

SELECT  COALESCE(s.EmployeeID, projectID) AS employeeID
,       e.LastName
,       COALESCE(projectID, s.EmployeeID) AS 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

因为您的 projectid 等于员工 ID,所以如果联接返回 null 的 ProjectID 我们可以使用employeeid

于 2013-05-08T04:52:22.370 回答
2

NULL 值表示这 2 名员工没有任何项目。换句话说,没有 id 为 4,5 的项目

于 2013-05-08T04:42:59.250 回答
0

根据您的数据库结构,我假设一名员工正在为一个项目工作,并且所有时间表都只为该项目注册。我个人认为这不是一个好的数据库设置。它可能不用于在实际项目中存储真实数据。

于 2013-05-08T06:23:38.877 回答