SQL通过联结表从其他表中选择总和作为列
Posted
技术标签:
【中文标题】SQL通过联结表从其他表中选择总和作为列【英文标题】:SQL select sum from other table as a column via junction table 【发布时间】:2009-08-01 15:51:16 【问题描述】:我有 2 个常规表“Tasks”和“Employees”和一个连接表 EmployeeTasks,它们看起来像这样
任务
任务 ID 项目ID 持续时间员工
员工 ID 员工姓名员工任务
员工 ID 任务 ID我正在尝试找到一个 tsql 查询,该查询基于通用项目 ID 将提供每个员工花费的总时间和完成的任务数量的摘要。类似这样:
"Employee" | "Number of Tasks" | "Time Spent"
----------------------------------------
John | 5 | 123
Sam | 4 | 72
【问题讨论】:
没有零,谢谢!呵呵,没有作业我只是通常不使用数据库,并且正在努力了解 SQL。 【参考方案1】: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
【讨论】:
【参考方案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
【讨论】:
【参考方案3】:请注意,如果您需要为没有任务的员工显示时间,这会有所不同。
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
【讨论】:
以上是关于SQL通过联结表从其他表中选择总和作为列的主要内容,如果未能解决你的问题,请参考以下文章
从表中选择不同的记录并执行重复行的列总和(托盘、总和)。并显示重复的行一次[关闭]