在mysql查询中计算余额总和

时间:2019-02-27 16:17:09

标签: php mysql

我正在尝试生成“客户余额未清报告”。

我有两个表:customertransaction

客户

custid| custname
------+------------
1     | abc
2     | xyz 
3     | ben    
4     | angel

交易

tid| customerid  | amount
---+-------------+-------
1  | 1           | 100
2  | 4           | 300
3  | 2           | 130
4  | 2           | 500
5  | 3           | 100
6  | 1           | 35
7  | 4           | 104
8  | 1           | 25
9  | 3           | 50

我想要这样的结果:

Custname  | balance
----------+--------
abc       | 160
xyz       | 630
ben       | 150   
angel     | 404

1 个答案:

答案 0 :(得分:-1)

SELECT a.custname as custname 
     , sum(b.amount) as balance 
  from customer a
     , transaction b 
 where a.custid = b.customerid