Mysql拉一个计数,并按该计数分组

时间:2014-08-11 19:59:21

标签: mysql sql

很难准确解释我需要什么。我想要做的就是本月计算前5名获胜者。表格的结构(打开以改变它)是它记录每场比赛,球员的ids,获胜者和日期。

表格结构如下:id,p1id,p2id,dateAdded,status,winner。

这是我的拉动:

 SELECT COUNT(winner) AS totalCount FROM gameEnders 
 WHERE 
 status=0 AND 
 (YEAR(dateAdded) = YEAR(CURDATE()) AND MONTH(dateAdded) = MONTH(CURDATE())) 
 GROUP BY winner
 ORDER BY totalCount DESC LIMIT 5

我知道当我这样做时,这不会起作用,但这是我最好的猜测。我想要显示的是3然后是1(稍后将添加玩家名称加入)。获胜者ID有3个条目:2个,获胜者ID为1个条目:1。显示的是2,这是最高编号的获胜者的ID。

试图尽可能清楚地表达我想做的事情。如果可能,或者如果有人需要更多信息,请告诉我。

2 个答案:

答案 0 :(得分:1)

只需将winner添加到select语句中,您本月就应该有一个获胜者降序列表......

Select winner, 
       Count(*) AS totalCount 
From   gameEnders 
Where  status=0 
And    Year(dateAdded) = Year(CurDate()) 
And    Month(dateAdded) = Month(CurDate())
Group By winner
Order By Count(*) DESC 
Limit 5

答案 1 :(得分:0)

试试这个:

SELECT winner
from
(
SELECT 
    winner, 
    COUNT(*) AS totalCount 
FROM gameEnders 
WHERE status=0 AND (YEAR(dateAdded) = YEAR(CURDATE()) AND MONTH(dateAdded) = MONTH(CURDATE())) 
GROUP BY winner
) ranked_winners
ORDER BY totalCount DESC
LIMIT 5;