Mysql将表B的总和(B.column)加到5的总和,添加到表A的每一个新行

时间:2017-04-29 23:01:53

标签: mysql

我想总结来自表B Bonus.value 的值,其中兑换= 0 ,最多为5的总和,这样当它总和达到5时就会得到已添加到表A购买的结果表中,其中兑换= 0 customer_id 相关,如下图所示

目前我有这个,但返回每条记录的总和:

select *,(select Sum(b.value) from bonus b WHERE b.Bonus_type='purchase' AND 
b.Customer_id=1 AND b.redeemed=0) AS 'pbonus', (select Sum(b.value) from bonus b WHERE 
b.Bonus_type='referral' AND b.Customer_id=1 AND b.redeemed=0) AS 'rbonus' FROM purchase p 
where p.Customer_id = 1 AND p.redeemed = 0; 

(Purchase - Table A, Bonus -Table B and Result Table

1 个答案:

答案 0 :(得分:-1)

您需要使用" group by customer_id"当您需要总结相同的客户ID时