[英]Summing two columns then subtracting the sums
Here is my table. 这是我的桌子。
pk | transactionID
| description
| transactionDate
| transactionAmount
| accountRecieve
| accountSend
Those are my columns. 这些是我的专栏。 I need to find the balance given an accountNumber through a query.
我需要通过查询找到给定accountNumber的余额。 To do this I have to SUM transactionAmount where accountSend = 127 and then SUM transactionAmount where accountRecieve = 127 and then subtract the first sum from the second sum and show it in one result.
为此,我必须先对accountAend = 127的transactionAmount求和,然后再使accountRecieve = 127的SUM transactionAmount求和,然后从第二个总和中减去第一个总和,并在一个结果中显示它。
I can explain it but I have no idea how to execute this in SQL. 我可以解释它,但我不知道如何在SQL中执行此操作。 Can anyone please help.
谁能帮忙。
One option uses conditional aggregation: 一种选择是使用条件聚合:
SELECT
SUM(IIF(accountReceive = 127, transactionAmount, 0)) -
SUM(IIF(accountSend = 127, transactionAMount, 0)) AS diff
FROM yourTable;
The idea is to just make a single pass over the entire table, summing the transaction amount using the two criteria. 想法是仅对整个表进行一次传递,并使用两个条件对交易金额求和。
You can also express this using switch
: 您也可以使用
switch
来表达这一点:
SELECT SUM(SWITCH(accountReceive = 127, transactionAmount
accountSend = 127, - transactionAMount, 0,
1=1, 0
)
) AS diff
FROM yourTable;
This only uses one SUM()
and is more analogous to using CASE
in other databases. 这仅使用一个
SUM()
,与在其他数据库中使用CASE
更为相似。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.