2013-09-30 487 views
4

我想選擇誰擁有用戶的最大數微觀柱:SQL SELECT MAX(COUNT)

SELECT "name", count(*) FROM "users" 
    INNER JOIN "microposts" ON "microposts"."user_id" = "users"."id" 
    GROUP BY users.id 

,這將返回

"Delphia Gleichner";15 
"Louvenia Bednar IV";10 
"Example User";53 
"Guadalupe Volkman";20 
"Isabella Harvey";30 
"Madeline Franecki II";40 

但我只想選擇"Example User";53,(用戶誰有MAX微博計數)

我試圖添加HAVING MAX(count*),但這沒有奏效。

+0

做一個子查詢返回的最大微柱數和加入到其中,這/有,如果你是 – JsonStatham

+0

做一組它*很重要。沒有兩個DBMS在執行SQL「標準」時是相似的。 –

+0

'HAVING'只是應用於GROUP BY聚合列的where子句:所以你需要一個操作符。 –

回答

7

我想嘗試用ORDER BY最大DESC LIMIT 1,其中最大的是COUNT(*)領域。喜歡的東西:

SELECT "name", count(*) maximum FROM "users" 
    INNER JOIN "microposts" ON "microposts"."user_id" = "users"."id" 
GROUP BY users.id 
ORDER BY maximum DESC 
LIMIT 1 

我不」具有的MySQL現在,所以我在紙上做這(和它可能無法正常工作),但它只是一個方向。

+0

這個對我來說很好。 –

+0

但可能還有一種方法使用MAX函數 –

+0

這適用於最大值沒有關係的情況。如果有,那麼你正在擺脫其他最大值。 – AlwaysNull

0

也許是這樣的:

SELECT "name", count(*) 
FROM "users" 
INNER JOIN "microposts" ON "microposts"."user_id" = "users"."id" 
GROUP BY users.id 
HAVING COUNT(microposts) = (SELECT COUNT(microposts) 
         FROM users 
         GROUP BY microposts 
         ORDER BY COUNT(microposts) DESC 
         LIMIT 1) 

沒有測試它,但它可能工作

0
SELECT TOP 1 "name", count(*) AS ItemCount FROM "users" 
INNER JOIN "microposts" ON "microposts"."user_id" = "users"."id" 
GROUP BY users.id 
ORDER BY ItemCount DESC 
2
SELECT x.name, MAX(x.count) 
FROM (
SELECT "name", count(*) 
    FROM "users" INNER JOIN "microposts" ON "microposts"."user_id" = "users"."id" 
    GROUP BY users.id 
) x 
0

這很簡單,你可以嘗試:

SELECT "name", MAX(count_num) FROM 
(SELECT "name", count(*) as count_num 
FROM "users" INNER JOIN "microposts" ON "microposts"."user_id" = "users"."id" 
GROUP BY users.id) x