我想跟踪不同部门在工作中进行的调查。 通过使用“分组依据”并计算匹配数量,这很容易做到。
SELECT Departments.DepartmentName, count(*) as [survey count]
FROM Departments INNER JOIN
Surveys ON Departments.DepartmentID = Surveys.DepartmentID
GROUP BY Departments.DepartmentName
但这仅显示已完成调查的部门。如何将未完成调查结果列表的部门作为零计数?
更新
SELECT Departments.DepartmentName AS Department,
COUNT( Surveys.DepartmentID) AS [survey count]
, Departments.DepartmentID
FROM Surveys FULL OUTER JOIN
Departments ON Surveys.DepartmentID = Departments.DepartmentID
GROUP BY Departments.DepartmentName, Departments.DepartmentID
答案 0 :(得分:4)
您需要一个“左外连接”而不是“内连接” - 这将在输出中生成行,其中所有与“survey”对应的列为null,其中没有匹配连接条件。
您需要将查询更新为“count(Surveys.DepartmentID)”或“sum(survey.departmentID不为null,然后是1,否则为0)”,以避免将这些行计为单个提交。< / p>
答案 1 :(得分:3)
将INNER JOIN
替换为LEFT JOIN
。即使没有相关的调查,它也会选择所有部门。
答案 2 :(得分:2)
只需将INNER JOIN更改为LEFT JOIN并将COUNT()更改为仅引用SURVEYS。那可能就像那时一样。
SELECT Departments.DepartmentName,
count(Surveys.DepartmentID) as [survey count]
FROM Departments LEFT JOIN
Surveys ON Departments.DepartmentID = Surveys.DepartmentID
GROUP BY Departments.DepartmentName
答案 3 :(得分:1)
SELECT Departments.DepartmentName, count(Surveys.DepartmentID) as [survey count]
FROM Departments
LEFT OUTER JOIN Surveys
ON Departments.DepartmentID = Surveys.DepartmentID
GROUP BY Departments.DepartmentName
答案 4 :(得分:1)
SELECT Departments.DepartmentName, count(Surveys.*) as [survey count]
FROM Departments
LEFT JOIN Surveys ON Departments.DepartmentID = Surveys.DepartmentID
GROUP BY Departments.DepartmentName
请注意 LEFT 加入和计数的变化(调查。*)