我有一张名为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;
请帮我解决这个问题。
答案 0 :(得分:4)
我建议您在Primary Key
表格中添加temp_reading
。 (阅读有关Primary Keys的更多信息)此密钥每行唯一。然后你可以尝试这个查询:
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尝试过。
答案 1 :(得分:1)
select id,sum(consumption) as total
from temp_reading
group by id;
我建议您没有相同的ID
(1,1,1.2,2 ......)
答案 2 :(得分:0)
试试这个:
SELECT id, consumption, IF(@s=@s:=id, @s2:=@s2+consumption, @s2:=consumption) AS total
FROM temp_reading, (SELECT @s:=0, @s2:=0);