我想在我的数据库中计算客户的“余额”。
Customer Table
-----------------
1 - Frank
2 - Bob
Invoice Table
---------------------------------------------------
id | customer_id | amount_due | credit_due
---------------------------------------------------
1 | 1 | $10 |
---------------------------------------------------
2 | 1 | | $6
---------------------------------------------------
这是查找客户信息的典型sql语句。
SELECT id, name FROM CUSTOMER WHERE id = ?
如果我还要检索余额,我这样做:
SELECT a.*, b.* FROM
(SELECT id, name FROM CUSTOMER WHERE id = ?) AS a,
(SELECT SUM(amount_due - credit_due) AS balance FROM INVOICE WHERE cus_id = ?) AS b
运行此结果:
--------------------
id | name | balance
---------------------
1 | Frank | $4
这在检索一个客户时效果很好,但是如果我想进行更一般的搜索怎么办?喜欢加载所有客户?
这是我想要的输出
--------------------
id | name | balance
---------------------
1 | Frank | $4
---------------------
2 | Bob | $0
答案 0 :(得分:2)
我认为你只会使用聚合:
select c.customer_id, c.name,
( coalesce(sum(i.amount_due), 0) - coalesce(sum(i.credit_due), 0) ) as balance
from customer c join
invoice i
on i.customer_id = c.customer_id
group by c.customer_id, c.name;
我应该注意,如果金额字段是NULL
,那么表达式sum(amount_due - credit_due)
就没有达到预期效果。