想要显示每月分组的最高得分者详细信息

时间:2014-03-12 14:07:15

标签: php mysql

我有一张数据表 数据库表格看起来像

   id   |   name   |  userid  |  score   |      date      |
   ------------------------------------------------------------
    1   |   john   |    4     |   233    |  2014-02-02 
    2   |   mary   |    5     |  1256    |  2013-02-05  
    3   |   john   |    6     |   100    |  2013-03-08 
    4   |   elvis  |    7     |   123    |  2013-03-04 
    5   |   john   |    2     |   1234   |  2013-03-02

现在我想展示每个月最高得分者的详细信息。我的检索数据输出将是json格式

目前我的查询输出显示

"monthly_winners":[
    {
        "id":"1",
        "score":"233",
        "month":"Feb"
    },
    {
        "id":"3",
        "score":"100",
        "month":"Mar"
    }
],

但它会是

"monthly_winners":[
    {
        "id":"2",
        "score":"1256",
        "month":"Feb"
    },
    {
        "id":"5",
        "score":"1234",
        "month":"Mar"
    }
],

我无法理解我的查询中的错误

我的查询是

SELECT id,score, DATE_FORMAT(`date`,'%b' ) AS month FROM `winner`  GROUP BY month ORDER BY score DESC

2 个答案:

答案 0 :(得分:1)

SELECT x.*
  FROM my_table x
  JOIN 
     ( SELECT DATE_FORMAT(date,'%Y%m')yearmonth
            , MAX(score) max_score 
         FROM my_table 
        GROUP 
           BY DATE_FORMAT(date,'%Y%m')
     ) y
    ON y.yearmonth = DATE_FORMAT(x.date,'%Y%m')
   AND y.max_score = x.score;

答案 1 :(得分:0)

只是为了感兴趣并跟进草莓的答案(这可能涵盖了您的要求),如果2个人在一个月内共享相同的最高分,则以下内容应始终为您提供一个匹配的ID /名称(我刚刚随机选择以获取具有最高id的用户的详细信息。

SELECT winner.id, winner.score, DATE_FORMAT(`date`,'%Y%m' ) AS `month`
FROM
(
    SELECT DATE_FORMAT(`date`,'%Y%m' ) AS aMonth, MAX(score) AS max_score
    FROM winner
    GROUP BY aMonth
) Sub1
INNER JOIN
(
    SELECT DATE_FORMAT(`date`,'%Y%m' ) AS aMonth, score, MAX(id) AS max_id
    FROM winner
    GROUP BY aMonth, score
) Sub2
ON Sub2.score = Sub1.max_score
AND Sub2.aMonth = Sub1.aMonth
INNER JOIN winner
ON winner.score = Sub1.max_score
AND DATE_FORMAT(winner.`date`,'%Y%m' ) = Sub1.aMonth
AND winner.id = Sub2.max_id