MYSQL:使用GROUP BY逐行增加价值

时间:2018-11-12 11:27:28

标签: mysql group-by

我想逐月累加仪表值。我的数据如下:

| Date       | Energy_produced |
--------------------------------
| 2011-01-01 | 12              |  
| 2017-01-02 | 23              |  
| 2017-01-03 | 25              |  
...
| 2011-02-01 | 11              |  
| 2017-02-02 | 12              |  
| 2017-02-03 | 17              | 

GROUP BY将得出每个月“ Energy_produced”值的总和,但我希望将其总和得到:

| Month   | Energy_produced_added_up |
--------------------------------------
| 2011-01 | 60                       |  
| 2017-02 | 100                      | 

我阅读了很多文章,并了解可以使用变量:

set @result := 0;
SELECT 
    DATE_FORMAT(t.Datum_Maand, '%m') AS measurement_month, 
    DATE_FORMAT(t.Datum_Maand, '%Y') AS measurement_year,
    (@result := @result + SUM(t.Geg_Maand)) AS SUMME
FROM tgeg_maand AS t
GROUP BY measurement_year, measurement_month
ORDER BY measurement_year, measurement_month

对于GROUP BY,该值不累加。上面的语句显示与以下结果相同的结果:

SELECT 
    DATE_FORMAT(t.Datum_Maand, '%m') AS measurement_month, 
    DATE_FORMAT(t.Datum_Maand, '%Y') AS measurement_year,
    SUM(t.Geg_Maand) AS SUMME
FROM tgeg_maand AS t
GROUP BY measurement_year, measurement_month
ORDER BY measurement_year, measurement_month

我在做什么错了?

谢谢

2 个答案:

答案 0 :(得分:1)

您需要先按月求和,然后再对月值求和。为此,您需要将原始查询变成子查询:

set @result := 0;
SELECT measurement_month, measurement_year,
       @result := @result + monthly_sum AS SUMME
FROM (SELECT DATE_FORMAT(t.Datum_Maand, '%m') AS measurement_month, 
             DATE_FORMAT(t.Datum_Maand, '%Y') AS measurement_year,
             SUM(t.Geg_Maand) AS monthly_sum
      FROM tgeg_maand AS t
      GROUP BY measurement_year, measurement_month) mm
ORDER BY measurement_year, measurement_month

答案 1 :(得分:0)

使用此查询

SELECT 
    DATE_FORMAT(t.Datum_Maand, '%m') AS measurement_month, 
    DATE_FORMAT(t.Datum_Maand, '%Y') AS measurement_year,
    SUM(t.Geg_Maand) AS SUMME
FROM tgeg_maand AS t
GROUP BY measurement_year, measurement_month
ORDER BY measurement_year, measurement_month