SQL列出处理大多数客户的代表

时间:2013-01-13 05:40:32

标签: sql count group-by

我有2个表SALESREPCUSTOMER 我需要找出哪个salesrep拥有大多数客户

我有以下代码:

select rep_lname, count(cust_num) 
from customer inner join salesrep 
on customer.REP_NUM = SALESREP.REP_NUM 
group by rep_lname

这为我提供了每个salesrep拥有的客户数量的所有行,而我只需要一行拥有最多客户。

如何找到MAX num of customers的行?

2 个答案:

答案 0 :(得分:1)

select rep_lname, count(cust_num) 
from customer inner join salesrep 
on customer.REP_NUM = SALESREP.REP_NUM 
group by rep_lname order by count(cust_num) desc limit 1;

我确信使用having有另一种方式,但我现在似乎无法弄明白。也许其他人会加入其中?

答案 1 :(得分:0)

SELECT TOP 1 WITH TIES rep_lname, COUNT(cust_num)
FROM customer inner join salesrep 
  ON customer.REP_NUM = SALESREP.REP_NUM 
GROUP BY rep_lname
ORDER BY count(cust_num) DESC