3

我有一张桌子叫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

3 回答 3

4

我建议你Primary Key在你的temp_reading桌子上添加一个。(阅读有关主键的更多信息)此键每行都是唯一的。然后你可以试试这个查询:

SELECT TR.id
  , TR.consumption
  , TR.consumption + IFNULL(SUM(TR2.consumption), 0) AS Total
  FROM temp_reading TR
  LEFT JOIN temp_reading TR2 ON TR.id = TR2.id AND TR.pk > TR2.pk
  GROUP BY TR.pk;

我已经在SQL Fiddle中尝试过。

于 2012-11-27T08:01:31.550 回答
1
     select id,sum(consumption) as total 
     from temp_reading 
     group by id;

我建议你没有相同的ID(1,1,1.2,2 ...)

于 2012-11-27T06:51:01.017 回答
0

尝试这个:

SELECT id, consumption, IF(@s=@s:=id, @s2:=@s2+consumption, @s2:=consumption) AS total
FROM temp_reading, (SELECT @s:=0, @s2:=0);
于 2012-11-27T06:44:47.243 回答