mysql:通过groupby逐行增加值

btqmn9zl  于 2021-06-18  发布在  Mysql
关注(0)|答案(2)|浏览(239)

我想逐月计算 Jmeter 值。我的数据如下:

| 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\u Producted”值的总和,但我希望将总和相加得到:

| 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

我做错什么了?
谢谢

fwzugrvs

fwzugrvs1#

使用此查询

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
qco9c6ql

qco9c6ql2#

您需要先按月求和,然后对每月的值求和。为此,您需要将原始查询转换为子查询:

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

相关问题