Sql 在对联接表使用COUNT()时是否包含其他字段?
我将学习SQL,并在其中一个练习中遇到麻烦。“获取每位员工负责的客户数量”(我希望翻译可以)。我发现了以下几点:Sql 在对联接表使用COUNT()时是否包含其他字段?,sql,join,count,Sql,Join,Count,我将学习SQL,并在其中一个练习中遇到麻烦。“获取每位员工负责的客户数量”(我希望翻译可以)。我发现了以下几点: SELECT emp.EmployeeId, COUNT(cus.SupportRepId) AS Customers FROM Employee AS emp JOIN Customer AS cus ON cus.SupportRepId = emp.EmployeeId GROUP BY emp.EmployeeId 到目前为止,结果是正确的: EmployeeId
SELECT emp.EmployeeId, COUNT(cus.SupportRepId) AS Customers
FROM Employee AS emp JOIN Customer AS cus
ON cus.SupportRepId = emp.EmployeeId
GROUP BY emp.EmployeeId
到目前为止,结果是正确的:
EmployeeId Customers
-------------------------
3 21
4 20
... ...
现在,我认为在结果中添加员工的数据(例如“employee”表中的JobTitle)也不错,但这似乎不起作用:
SELECT emp.EmployeeId, emp.JobTitle, COUNT(cus.SupportRepId) AS Customers
FROM Employee AS emp JOIN Customer AS cus
ON cus.SupportRepId = emp.EmployeeId
GROUP BY emp.EmployeeId
我不明白为什么。为了获得预期结果,我应该做什么:
EmployeeId JobTitle Customers
------------------------------------------------
3 Key Account Manager 21
4 Business Area Manager 20
... ...
我希望你能帮忙。在此之前非常感谢。您可以通过以下方式将其放入
组:
SELECT e.EmployeeId, e.JobTitle, COUNT(c.SupportRepId) AS Customers
FROM Employee e JOIN
Customer c
ON c.SupportRepId = e.EmployeeId
GROUP BY e.EmployeeId, e.JobTitle;
或者,您可以在加入之前使用相关子查询或聚合:
SELECT e.*, c.Customers
FROM Employee e JOIN
(SELECT c.SupportRepId, COUNT(c.SupportRepId) AS Customers
FROM Customer c
GROUP BY c.SupportRepId
) c
ON c.SupportRepId = e.EmployeeId;