Sql查询难以求和

时间:2014-10-25 11:47:50

标签: mysql sql

我有一张表Customers ( id | name ),其名称和名称为fornitori, 和另一张表Money (id | idcustomers | give | have )

Givehaveint字段,客户提供的资金和金额可以创造余额。

我想创建一个查询,为每个客户显示名称和不同 其中SUM(GIVE) - SUM(HAVE)

money.idcustomers = customers.id

2 个答案:

答案 0 :(得分:1)

按客户ID分组应该可以解决问题:

SELECT Customers.name, SUM(GIVE) - SUM(HAVE) total
FROM Customers
JOIN Money ON Money.idcustomers = Customers.id
GROUP BY Customers.id

SQL小提琴演示; http://sqlfiddle.com/#!2/339032/2

答案 1 :(得分:0)

SELECT C.name, (SUM(M.give)-SUM(M.Have)) AS total
FROM Customors C, Money M
WHERE C.id = M.idcustomers
ORDER BY C.name
GROUP BY C.name