使用mysql中的当前值添加先前的值

时间:2016-02-04 10:57:11

标签: mysql

我有两列,即zone和total_bill_amount,我想用列的当前值添加以前的值..我用过

 select  zone, total_bill_amount, sum(total_bill_amount) as Total_Bill
 from Cal_Amount  
 where cluster_number = 'clust 2' 
 group by zone,total_bill_amount;

 1. zone       total_bill_amount   Total_Bill                           

 2. ABC          45                    45                               

 3. PQR          78                    123                              

 4. XYZ          16                    139

45 = 45 45+78 = 123 123 + 16 = 139

1 个答案:

答案 0 :(得分:1)

您可以使用变量:

select zone, total_bill_amount,
       @total := @total + total_bill_amount AS Total_Bill
from Cal_Amount
where cluster_number = 'clust 2'        
cross join (select @total := 0) as var
order by zone

如果zone不是表格,则必须使用指定表格顺序的列替换zone