简体   繁体   English

MySQL - 得到总和()分组的最大()组

[英]MySQL - get sum() grouped max() of group

I have table structure like below.我有如下表结构。 Each row is one played game, each person can play many or none times in each month.每一行是一个玩过的游戏,每个人每个月可以玩很多次或不玩一次。

id  |  person  |  score  |   date  |
------------------------------------
1   |    32    |  444    | 2011-05 |
2   |    65    |  528    | 2011-05 |
3   |    77    |  455    | 2011-05 |
4   |    32    |  266    | 2011-06 |
5   |    77    |  100    | 2011-06 |
6   |    77    |  457    | 2011-06 |
7   |    77    |  457    | 2011-06 |
8   |    65    |  999    | 2011-07 |
9   |    32    |  222    | 2011-07 |

I am trying to get for each person sum of its best score in each month.我试图为每个人获得每个月的最佳分数总和。 S result of above should be:上面的 S 结果应该是:

 person  | SUM(ofbestofeachmonth)
---------------------------------
  32     |  932
  65     |  1527
  77     |  912

I know how to fetch the bests scores per userin month or some range我知道如何在一个月或某个范围内获取每个用户的最佳分数

SELECT person, date, MAX(score) FROM tabgames WHERE MONTH(date) = 6 GROUP BY person HAVING (score>0)

Because i need in the end output per quarter of year, now i am fetching best for each month and outside the MySQL i am adding.因为我最终每个季度都需要 output,所以现在我每个月都在获取最好的数据,并且在我添加的 MySQL 之外。

Now i am reading about group-wise max and still try to get excpected results.现在我正在阅读有关分组最大值的信息,但仍在尝试获得预期的结果。 Any help任何帮助

Subqueries:子查询:

SELECT person, SUM(best)
FROM
    (SELECT person, MAX(score) as best
    FROM tabgames
    WHERE MONTH(`date`) >= 1 AND MONTH(`date`) <= 6 
    GROUP BY person, MONTH(`date`)) as bests
GROUP BY person

Now the subquery is grouped by person and MONTH(date), so it will return a row for each month.现在子查询按人员和 MONTH(date) 分组,因此它将为每个月返回一行。

Select t.person,Max(t.Score) from 
(
Select person,Sum(Score) as Score,Month('Date') as [Month]  From tabgames
WHERE MONTH(`date`) >= 1 AND MONTH(`date`) <= 6 
GROUP BY PERSON,Month

) AS t

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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