SQL select sum from other table as a column via junction table

sqlsql-server-2005tsql

I have 2 regular Tables "Tasks" and "Employees" and one junction table EmployeeTasks simplified they look like this

Tasks

  • TaskID
  • ProjectID
  • Duration

Employee

  • EmployeeID
  • EmployeeName

EmployeeTasks

  • EmployeeID
  • TaskID

I am trying to find a tsql query that based on a common project ID would deliver a summary of the total time spent and number of tasks done by each employee. Similar to this:

"Employee" | "Number of Tasks" | "Time Spent"
----------------------------------------
John       |        5          |  123
Sam        |        4          |   72

Best Answer

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