2

I'm having a small problem with an aggregate function that I can't quite crack. I have to get a count of customers for each representative in my database - I can accomplish this - the second part of my is that I have to only display the representative with the highest number of customers.

So far I have;

SELECT Rep.RepNum, Count(Customer.RepNum) AS [CustomerCount]

FROM Rep INNER JOIN Customer ON Rep.RepNum = Customer.Repnum

GROUP BY Rep.RepNum

I know I'm probably going to have to use a nested query to solve this, but I'm not sure how to go about this problem. It has been fighting me for almost and hour, and ANY help would be greatly appreciated.

2 Answers 2

1

Try:

 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
2
  • This did Exactly What I needed it to! Thank you so much! I can finally get some sleep now, haha.
    – CoreyD
    Jul 10, 2014 at 6:19
  • Nice to hear that @CoreyD. Happy coding and GOD bless.
    – Edper
    Jul 10, 2014 at 6:21
0

Maybe this will do:

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));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.