2016-04-21 49 views
1

我有這個疑問如何從GROUP BY中獲取COUNT(*)的最大值?

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

它提供了以下結果:

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

如何查詢PnameNum,使其返回具有最高計數的元素名稱?

結果應該是這樣的:

InkjetPrinters 10 
LaserPrinters 10 
+1

您正在使用什麼數據庫? –

+0

我自己在本地主機上。 Idk – user3436529

+0

Xampp上的SQL。現在問題已解決,謝謝。 – user3436529

回答

0

您可以使用從子查詢中指定HAVING子句。

在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 
) 
+2

SELECT Pname,COUNT(*)AS num FROM employee,project WHERE Dno = Dnum GROUP BY Pname HAVING NUM =(SELECT COUNT(*)FROM employee JOIN project ON Dno = Dnum GROUP BY Pname ORDER BY COUNT(*)DESC LIMIT 1 ) 它的工作原理!謝謝 – user3436529

+1

@ user3436529如果這對你有用,請不要猶豫,接受它。有許多用戶不會閱讀整篇文章,但只需找到明顯的答案。如果沒有答案被標記,他們只是離開帖子。 – Atif