0

我在此有一个名为 temp_reading 的表,以下列存在并且消费是主键:

id consumption total
1  100
1  200
1  300
1  400
2  50
2  100
3  200
4  250

现在我想将总计显示为

id   consumption  total
1    100          100
1    200          300
1    300          600
1    300          900
2    50           50
2    100          150
3    200          200
4    250          250

是否可以像上面那样显示我尝试了以下查询

select id,consumption,sum(consumption) as total 
from temp_reading 
group by consumption;

请帮我解决这个问题

4

1 回答 1

5
SELECT  id, 
        consumption,
         @accum:=@accum + a.runningTotal AS TOTAL
FROM 
    (  
      SELECT  id, 
              consumption, 
              SUM(consumption) AS runningTotal
      FROM table1
      GROUP BY id, consumption
      ORDER BY id, consumption
    ) a , (SELECT @accum := 0) s;
于 2012-11-19T07:45:51.893 回答