[英]How to calculate balance from credit and debit?
How to get balance amount based on credit CRD
and debit DEB
for each customer cust
from following txn_tbl
table如何根据信用获得余额CRD
和借记DEB
为每个客户cust
从以下txn_tbl
表
SQL> SELECT * FROM txn_tbl;
CUS AMT TXN_CDE
--- ---------- ----------
A 500 CRD
B 400 CRD
A 350 CRD
C 235 DEB
C 800 CRD
B 132 DEB
D 673 CRD
This is the query that i had tried这是我试过的查询
SELECT cust, LAG(amt,1,0) OVER (PARTITION BY cust ORDER BY cust) "Bal"
FROM
(SELECT cust, SUM(amt)amt
FROM txn_tbl
GROUP BY cust, txn_cde
ORDER BY 2);
If you want the running balance, you can do a window sum with conditional logic:如果您想要运行余额,您可以使用条件逻辑进行窗口总和:
select
t.*,
sum(case when txn_cde = 'CRD' then amt else -amt end)
over(partition by cus order by id) running_balance
from mytable
For this to work, you need a column that can be used to order the records;为此,您需要一个可用于对记录进行排序的列; I assumed id
.我假设id
。
On the other hand, if you want the overall balance per customer (so just one record per customer in the resultset), you can use the same logic with aggregation (and you don't need an ordering colum):另一方面,如果您想要每个客户的总体余额(因此结果集中每个客户只有一个记录),您可以使用与聚合相同的逻辑(并且您不需要排序列):
select cus, sum(case when txn_cde = 'CRD' then amt else -amt end) balance
from mytable
group by cus
You can just sum up your amounts.你可以总结一下你的金额。 The trick is to make your credit (or debit, it's not clear) a negative:诀窍是使您的信用(或借方,尚不清楚)成为负数:
SELECT cust, Sum(CASE WHEN TXN_CODE = 'DEB' THEN -1 ELSE 1 END * amt) as
FROM txn_tbl
GROUP BY cust
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.