Jump to content

group by, count then max query help


golfaddict2005

Recommended Posts

find the employee who has served the most customers:

 

So i am close with the limit however, if there are multiple employees that have helped the most customers (ie 3 employess have helped 10 customers) it only selects the top 1. i think it has to be done with the 'in' function with group by and count.  thanks in advance for your help.

 

 

SELECT e.emp_name, count(*) helped

FROM employee e, sales s

WHERE e.employee_no=s.employee_no

group by s.employee_no

order by helped DESC

limit 1

 

 

maybe like this (except it doest work)

 

SELECT e.emp_name

FROM employee e, sales s

WHERE e.employee_no=s.employee_no and max(

SELECT count(cust_no)

FROM sales s

group by s.employee_no)

 

 

thanks again! 

Link to comment
https://forums.phpfreaks.com/topic/136298-group-by-count-then-max-query-help/
Share on other sites

How about:

 

SELECT e.emp_name
FROM employee AS e
INNER JOIN 
( SELECT employee_no, COUNT(*) AS cnt FROM sales GROUP BY employee_no
HAVING cnt = ( SELECT MAX(cnt) FROM ( SELECT COUNT(*) AS cnt FROM sales GROUP BY employee_no ) )
) s ON ( s.employee_no=s.employee_no )

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.