我有2个常规表“任务”和“员工”和一个联结表EmployeeTasks简化它们看起来像这样
任务
员工
EmployeeTasks
我正在尝试找到一个基于公共项目ID的tsql查询,它会提供每个员工花费的总时间和完成的任务数量的摘要。与此类似:
"Employee" | "Number of Tasks" | "Time Spent"
----------------------------------------
John | 5 | 123
Sam | 4 | 72
答案 0 :(得分:2)
SELECT E.EmployeeName, COUNT(T.TaskID) AS [Number of Tasks], SUM(T.Duration) as [Time Spent]
FROM Employee E, EmployeeTasks ET, Tasks T
WHERE ET.EmployeeID = E.EmployeeID AND ET.TaskID = T.TaskID
GROUP BY E.EmployeeName
答案 1 :(得分:2)
试试这个:
Select EmployeeName,
Count(et.TaskId) NumTasks,
Sum(T.Duration) TimeSpent
From Employees E
Left Join (EmployeeTasks eT Join Tasks T
On T.TaskId = eT.TaskId)
On eT.EmployeeId = E.EmployeeId
Where ProjectId = @ProjectId
Group By EmployeeName
这将为所有员工 - 项目组合
Select EmployeeName, ProjectId,
Count(et.TaskId) NumTasks,
Sum(T.Duration) TimeSpent
From Employees E
Left Join (EmployeeTasks eT Join Tasks T
On T.TaskId = eT.TaskId)
On eT.EmployeeId = E.EmployeeId
Group By EmployeeName, ProjectId
答案 2 :(得分:0)
请注意,如果您需要为没有任务的员工显示时间,则会有所不同。
SELECT Count(TaskID) as NumOfTasks, Sum(Duration) as TimeSpent
FROM Employee
INNER JOIN EmployeeTasks on Employee.EmployeeID = Tasks.EmployeeID
INNER JOIN Tasks on EmployeeTasks.TaskID = Tasks.TaskID
WHERE ProjectID = @ProjectID
GROUP BY EmployeeID
如果您想要员工姓名,请将其作为子选择加入
SELECT EmployeeName, NumOfTasks, TimeSpent
FROM Employees
INNER JOIN (insert select here) TaskSummary on Employees.EmployeeID = TaskSummary.EmployeeID