Oracle-按条件查找列之间的差异

时间:2019-10-02 15:38:02

标签: sql oracle

带有操作的表:

asnyc function

我必须找到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

下一步,我需要所有帐户(按帐户)的余额,然后我将可以按客户(仅JOIN和SUM)以及0和max的帐户(通过相同方法)计算余额

2 个答案:

答案 0 :(得分:2)

您可以将每个传输分为发送者和接收者,然后按客户汇总。

以下给出了所有来自转账的客户的总数

select a.id_customer, sum(amount) as balance
from ((select id_account_sender as id_account,- amount_transfer as amount
       from operations o
      ) union all
      (select id_account_receiver, amount_transfer
       from operations o
      )
     ) o join
     accounts a
     on a.id = o.id_account
order by sum(amount);

答案 1 :(得分:2)

这将起作用:

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 ;

检查小提琴: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  ;

检查小提琴: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;

检查小提琴:http://sqlfiddle.com/#!4/61fec2/42

谢谢!!!! :-)