简体   繁体   English

Mysql 两个不同列的减和与连接 - 使用 Symfony 查询生成器

[英]Mysql Minus Sum Of Two Different Columns With Join - Using Symfony Query Builder

I've got two tables:我有两张桌子:

Account: id, name
Transaction: account_id,payment,charge

The transactions links to the account, and the transaction can either be a payment or a charge.交易链接到帐户,交易可以是付款或收费。 What I'm looking to do is in a single query, sum all the payments and minus the sum of all the charges so give the overall balance.我要做的是在一个查询中,将所有付款相加并减去所有费用的总和,从而得出总体余额。

I'm not great with mysql queries when they get this complex, but I can get the sum of the payments easily enough:当 mysql 查询变得如此复杂时,我并不擅长,但我可以很容易地得到付款的总和:

SELECT SUM(I.payment), A.* FROM propertyLettingAccountNew A INNER JOIN lettings_account_statement_item I ON I.letting_account_id = A.id GROUP BY A.id

So this is giving me the over all payment amount but I'm not sure how to sum the charge column and subtract it from the payment sum.因此,这给了我全部付款金额,但我不确定如何对费用列求和并从付款金额中减去。 I'm going to be using the symfony query builder for running this query once it's figured out if that makes a difference.我将使用 symfony 查询生成器来运行此查询,一旦确定是否会产生影响。

You can subtract charge from payment for each transaction and sum the results:您可以从每笔交易的付款中扣除费用并将结果相加:

SELECT a.id, a.name,
       SUM(COALESCE(t.payment, 0) - COALESCE(t.charge, 0)) balance
FROM Account a INNER JOIN Transaction t
ON t.account_id = a.id
GROUP BY a.id, a.name 

I use COALESCE() just in case there are nulls in the columns.我使用 COALESCE() 以防列中有空值。
If there aren't any nulls:如果没有任何空值:

SELECT a.id, a.name,
       SUM(t.payment - t.charge) balance
FROM Account a INNER JOIN Transaction t
ON t.account_id = a.id
GROUP BY a.id, a.name 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM