如何在postgres SQL查询中实现数学表达式?
How to achieve mathematical expression in postgres SQL query?
我有一种要求从 PostgreSQL 数据库 table.
中找出 "Main Balance"
这里,逻辑也很简单,
Main Balance = Credit + Refund - Debit
我也有一个数据库table,
Table 姓名:- Account
列:- id, source_account_number, destination_account_number, transaction_type, amount, creation_date_time
此处,transaction_type
可能具有以下一组可能值,CREDIT、REFUND、DEBIT.
现在,我想知道我的 A/c 余额是多少,那么逻辑应该是这样的,
Main Balance = sum of all CREDIT
entries + sum of all REFUND
entries -
sum of all DEBIT
entries.
所以基本上,我试图通过单个查询来实现这一点。
比如(明知道不对还是让我画),
select sum(amount) from Account where destination_account_number = 'XYZ' and transaction_type in ('CREDIT', 'REFUND');
但是它 return 只会 存入 金额本身,DEBIT 呢?
显然我们也可以恢复这些,但它正在促进多个查询。
任何人都可以帮助我通过最简单、优化的方式来实现此功能吗?
对于所有表现出兴趣的人来说,任何帮助都会非常感激!!
更新 -
在这里,transaction_type
可能有以下一组可能的值,CREDIT、REFUND、DEBIT、OTHERS、PENDING、EXPIRED。
现在,请考虑主要余额逻辑:- CREDIT + REFUND - DEBIT where PENDING, EXPIRED Money will be skipped in a main-balance calculation.
这可以通过条件聚合来完成。
select sum(case when transaction_type in ('CREDIT', 'REFUND') then amount else -amount end)
from Account
where destination_account_number = 'XYZ'
我有一种要求从 PostgreSQL 数据库 table.
中找出 "Main Balance"这里,逻辑也很简单,
Main Balance = Credit + Refund - Debit
我也有一个数据库table,
Table 姓名:- Account
列:- id, source_account_number, destination_account_number, transaction_type, amount, creation_date_time
此处,transaction_type
可能具有以下一组可能值,CREDIT、REFUND、DEBIT.
现在,我想知道我的 A/c 余额是多少,那么逻辑应该是这样的,
Main Balance = sum of all
CREDIT
entries + sum of allREFUND
entries - sum of allDEBIT
entries.
所以基本上,我试图通过单个查询来实现这一点。
比如(明知道不对还是让我画),
select sum(amount) from Account where destination_account_number = 'XYZ' and transaction_type in ('CREDIT', 'REFUND');
但是它 return 只会 存入 金额本身,DEBIT 呢?
显然我们也可以恢复这些,但它正在促进多个查询。
任何人都可以帮助我通过最简单、优化的方式来实现此功能吗?
对于所有表现出兴趣的人来说,任何帮助都会非常感激!!
更新 -
在这里,transaction_type
可能有以下一组可能的值,CREDIT、REFUND、DEBIT、OTHERS、PENDING、EXPIRED。
现在,请考虑主要余额逻辑:- CREDIT + REFUND - DEBIT where PENDING, EXPIRED Money will be skipped in a main-balance calculation.
这可以通过条件聚合来完成。
select sum(case when transaction_type in ('CREDIT', 'REFUND') then amount else -amount end)
from Account
where destination_account_number = 'XYZ'