我有以下表格结构,
客户信息:
cust_id cust_name
1 nikhil
2 sam
账单信息:
bill_id cust_id bill_amount
7 1 10000
8 1 15000
9 2 6000
10 2 4000
付费信息:
paid_id cust_id paid_amount
11 1 5000
12 1 5000
13 2 5000
14 2 5000
现在我的输出应该显示客户支付的账单总和以及该客户支付的总金额和余额
输出
cust_id total_bill total_paid balance
1 25000 10000 15000
2 10000 10000 0
例如,对于 cust_id = 2,
total_bill= 10000 + 15000
total_paid = 5000 + 5000
balance = total_bill - total_paid
在sql中执行此操作的便捷方法是什么?任何示例查询?
这是我已经尝试过的
SELECT distinct c.cust_id
, sum(b.bill_amount) as total_bill
, SUM(p.paid_amt) AS totalpaid,sum(b.bill_amount) - SUM(p.paid_amt) AS balance
FROM cust_info c
INNER JOIN bill_info b ON c.cust_id = b.cust_id
INNER JOIN paid_info p ON p.cust_id= b.cust_id group by p.cust_id;