我的聚合函数存在一个小问题,我无法解决。 我必须为我的数据库中的每个代表计算客户数量 - 我可以做到这一点 - 我的第二部分是我必须只显示拥有最多客户的代表。
到目前为止,我有;
SELECT Rep.RepNum, Count(Customer.RepNum) AS [CustomerCount]
FROM Rep INNER JOIN Customer ON Rep.RepNum = Customer.Repnum
GROUP BY Rep.RepNum
我知道我可能不得不使用嵌套查询来解决这个问题,但我不确定如何解决这个问题。几乎每小时都在和我作战,任何帮助都会非常感激。
答案 0 :(得分:1)
尝试:
SELECT TOP 1 Rep.RepNum,
Count(Customer.RepNum) AS [CustomerCount]
FROM Rep
INNER JOIN Customer ON Rep.RepNum = Customer.Repnum
GROUP BY Rep.RepNum
ORDER BY COUNT(Customer.RepNum) DESC
答案 1 :(得分:0)
也许会这样做:
SELECT Rep.RepNum, Count(Customer.RepNum) AS [CustomerCount]
FROM Rep INNER JOIN Customer ON Rep.RepNum = Customer.Repnum
GROUP BY Rep.RepNum
HAVING Count(Customer.RepNum) = (
Select max([CustomerCount])
FROM (SELECT Rep.RepNum,
Count(Customer.RepNum) AS [CustomerCount]
FROM Rep INNER JOIN Customer ON Rep.RepNum = Customer.Repnum
GROUP BY Rep.RepNum));