带有操作的表:
ID | ID_CUSTOMER | AMOUNT_TRANSFER | ID_ACCOUNT_SENDER | ID_ACCOUNT_RECEIVER|
我必须找到帐户余额为零和最大的 ID_CUSTOMER
。
余额是账户所有转账 AMOUNT_TRANSFER
的总差额。
我试图按客户查找所有转账金额,但我不知道如何找到差异:
SELECT
ACCOUNT.ID, SUM(O.AMOUNT_TRANSFER),
C2.SECOND_NAME AS Фамилия, C2.FIRST_NAME
FROM
ACCOUNT
JOIN
CUSTOMER C2 on ACCOUNT.ID_CUSTOMER = C2.ID
JOIN
OPERATION O on ACCOUNT.ID = O.ID_ACCOUNT_RECEIVER
GROUP BY
ACCOUNT.ID, C2.SECOND_NAME, C2.FIRST_NAME
示例数据:
ID ID_CUSTOMER AMOUNT_TRANSFER ID_ACCOUNT_SENDER ID_ACCOUNT_RECEIVER
1 1 5000 1 2
2 2 3000 1 2
3 1 2000 1 2
4 3 2000 2 3
5 3 1000 3 2
然后例如,
ID_ACCOUNT == 2 have 5000 + 3000 + 2000 + 1000 are received and 2000 are sended , total balance is 11000 - 2000 = 9000,
接下来我需要所有账户的余额(按账户)接下来我可以计算客户的余额(只是 JOIN 和 SUM)和 0 和最大值的账户(通过相同的方法)
最佳答案
这会起作用:
select m."a" account_id,nvl(((select sum(o."c") from Table1 o where o."e"=m."b")-
(select sum(o2."c") from Table1 o2 where o2."d"=m."b")),0)total_balance
from Table1 m ;
检查 fiddle :http://sqlfiddle.com/#!4/61fec2/14
下一个(客户余额):
select customer_id,sum(total_balance) from(select m."a" account_id,m."b"
customer_id,nvl(((select sum(o."c") from Table1 o where o."e"=m."b")-
(select sum(o2."c") from Table1 o2 where o2."d"=m."b")),0)total_balance
from Table1 m ) group by customer_id ;
检查 fiddle :http://sqlfiddle.com/#!4/61fec2/18
对于最后一个(对于余额为 0 和最大余额的帐户):
select e.account_id,case when rn=(select min(d.rn) from(select
n.*,dense_rank() over ( order by total_balance )rn from(select m."a"
account_id,nvl(((select sum(o."c") from Table1 o where o."e"=m."b")-
(select sum(o2."c") from Table1 o2 where o2."d"=m."b")),0)total_balance
from Table1 m)n)d) then 'minimum balance'
when rn=(select max(d.rn) from(select n.*,dense_rank() over ( order by
total_balance )rn from(select m."a" account_id,nvl(((select sum(o."c")
from Table1 o where o."e"=m."b")-
(select sum(o2."c") from Table1 o2 where o2."d"=m."b")),0)total_balance
from Table1 m)n)d) then 'maximum balance'
else
'intermediate balance'end
from
(select n.*,dense_rank() over ( order by total_balance)rn
from(select m."a" account_id,nvl(((select sum(o."c") from Table1
o where
o."e"=m."b")-
(select sum(o2."c") from Table1 o2 where
o2."d"=m."b")),0)total_balance
from Table1 m)n)e
order by e.account_id;
检查 fiddle :http://sqlfiddle.com/#!4/61fec2/42
谢谢!!!!!! :-)
关于sql - Oracle - 按条件查找列之间的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58204836/