我将学习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 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
... ...
我希望你能提供帮助。在此之前非常感谢。
答案 0 :(得分:1)
你可以把它扔进{{1}}:
{{1}}
或者,您可以在加入之前使用相关子查询或聚合:
{{1}}