我正在尝试列出处理大多数客户的代表
SELECT RTRIM(S.REP_FNAME) + ' ' + S.REP_LNAME AS [Representative], COUNT(C.REP_NUM) AS Customer(s) Per Rep]
FROM CUSTOMER C, SALESREP S
WHERE S.REP_NUM = C.REP_NUM
GROUP BY RTRIM(S.REP_FNAME) + ' ' + S.REP_LNAME
我的查询返回:
代表客户每位代表
胡安佩雷斯3
理查德赫尔4
瓦莱丽凯撒4
注意* Richard和Valerie就是我想要的。它应该显示为两个记录
如果您需要更多详细信息,请与我们联系。
答案 0 :(得分:0)
SELECT RTRIM(S.REP_FNAME) + ' ' + S.REP_LNAME AS [Representative], COUNT(C.REP_NUM) AS [Customer(s) Per Rep]
FROM CUSTOMER C
JOIN SALESREP S
ON S.REP_NUM = C.REP_NUM
GROUP BY RTRIM(S.REP_FNAME) + ' ' + S.REP_LNAME
HAVING COUNT(*) = (SELECT COUNTS FROM (SELECT TOP(1) REP_NUM, COUNT(REP_NUM) AS COUNTS GROUP BY REP_NUM ORDER BY COUNT(REP_NUM) DESC ))
或者你可以使用你给它的名字。:
ORDER BY [Customer(s) Per Rep] DESC
或者对于不太复杂的方法:
SELECT TOP(1) RTRIM(S.REP_FNAME) + ' ' + S.REP_LNAME AS [Representative], COUNT(C.REP_NUM) AS [Customer(s) Per Rep]
FROM CUSTOMER C, SALESREP S
WHERE S.REP_NUM = C.REP_NUM
GROUP BY RTRIM(S.REP_FNAME) + ' ' + S.REP_LNAME
ORDER BY [Customer(s) Per Rep] DESC