简体   繁体   中英

How do I get the max value of COUNT(*) from GROUP BY?

I have this query

SELECT Pname, COUNT(*) AS Num
FROM employee
JOIN project
  ON Dno = Dnum
GROUP BY Pname

which provides these results:

Pname                   Num
Computerization         3
DatabaseSystems         8
InkjetPrinters          10
LaserPrinters           10
Middleware              8
Newbenefits             3
OperatingSystems        8
ProductX                4
ProductY                4
ProductZ                4
Reorganization          1

How do I query Pname and Num such that it returns the element names with the highest count?

The results should look like this:

InkjetPrinters  10
LaserPrinters   10

You can use the HAVING clause specified from a sub query.

In MySQL

 SELECT Pname, COUNT(*) AS Num
 FROM employee
 JOIN project
   ON Dno = Dnum
 GROUP BY Pname
 HAVING COUNT(*) = (
  SELECT COUNT(*)
  FROM employee
  JOIN project
   ON Dno = Dnum
  GROUP BY Pname
  ORDER BY COUNT(*) DESC
  LIMIT 1
 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM