SQL:计算表中不存在的行

时间:2014-03-13 10:11:50

标签: c# sql sql-server linq-to-sql

我有两张名为:EmployeeTable& TaskAssignmentTable。 它们看起来像这样: tables formation
TaskAssignmentTable显示分配给员工的任务。为了将新任务分配给员工,我希望将任务分配给不同的人员,然后将任务分配给分配了最少任务的人员。
问题:在TaskAssignmentTable上使用正常count()导致此表: enter image description here
但我想要的是表之间的某种连接,它显示第一个表中存在的行数,第二个表中不存在,计数等于0,如下所示:

enter image description here

那么连接表并执行此类操作的SQL查询是什么? (可选:因为我使用C#Linq-2-SQL,如果有人可以为此编写LINQ语法,我将不胜感激。)

4 个答案:

答案 0 :(得分:2)

根据您的陈述,您需要一个LEFT OUTER JOIN,您希望第一个表中存在的行而不是第二个表中的行:

SELECT EmployeeID, Name, Count(TaskID) as CNT
FROM EmployeeTable e
LEFT JOIN TaskAssignmentTable t 
    ON e.employeeID = t.FKEmployeeID
GROUP BY EmployeeID, Name

答案 1 :(得分:1)

尝试

SELECT EmployeeID, Name, Count(TaskID) as CNT
FROM EmployeeTable emp
LEFT JOIN TaskAssignmentTable task on emp.employeeID = task.FKEmployeeID
GROUP BY EmployeeID, Name

答案 2 :(得分:0)

您需要OUTER JOIN两个表格(在您的情况下为LEFT JOIN):

SELECT EmployeeID, Name, Count(TaskID) as CNT
FROM EmployeeTable emp
LEFT JOIN TaskAssignmentTable task on emp.employeeID = task.FKEmployeeID
GROUP BY EmployeeID, Name

答案 3 :(得分:0)

为此你必须使用左外连接

SELECT EmployeeID, Name, Count(TaskID) as CNT
FROM EmployeeTable emp
LEFT OUTER JOIN TaskAssignmentTable task on emp.employeeID = task.FKEmployeeID
GROUP BY EmployeeID, Name

此查询的LINQ版本如下所示

var employees = from emp in dbContext.Employees
                join task in dbContext.TaskAssignmentTable 
                on emp.employeeID equals task.FKEmployeeID
                into tEmpWithTask
                from tEmp in tEmpWithTask.DefaultIfEmpty()
                group tEmp by new { emp.EmployeeID, emp.Name } into grp
                select new {
                  grp.Key.EmployeeID,
                  grp.Key.Name,
                  grp.Count(t=>t.TaskID != null)
                };