0

I have this table similar to MySQL - get sum() grouped max() of group

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

The result should be:

person  |  score  |   date  |   g   |   b   |   m   |
-----------------------------------------------------
  32    |   932   | 2012-05 |   1   |   3   |   1   |
  66    |  1527   | 2012-05 |   1   |   0   |   2   |
  77    |  1469   | 2012-05 |   2   |   0   |   3   |

But I couldn't achieve what I want to. I am trying to get for each person sum of its scores, g, m and b fields in each month. I'm very newbie about subqueries.

Thank you!

Community
  • 1
  • 1

1 Answers1

1

You can't just group by month, since the same month can appear in more than one year, so group by year as well, e.g.:

SELECT person, YEAR(`date`), MONTH(`date`), 
    SUM(score), SUM(b), SUM(g), SUM(m)
FROM MyTable
GROUP BY person, YEAR(`date`), MONTH(`date`)

If your date column is actually not a date type but a varchar or similar, and it contains yyyy-dd as shown, than you can just do:

SELECT person, `date`, 
    SUM(score), SUM(b), SUM(g), SUM(m)
FROM MyTable
GROUP BY person, `date`
D'Arcy Rittich
  • 167,292
  • 40
  • 290
  • 283