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

标签 sql oracle

带有操作的表:

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/

相关文章:

java - 使用 Oracle JDK 1.8 在 Amazon Linuc 上访问 WS02 API 管理器中的文件时出现 IO 错误

oracle - sqlplus session 只读

sql - 如何清除 Oracle 中的所有缓存项

c# - ASP.NET 项目的 Oracle 到 SQL Server 数据库迁移

mysql - 优化 SQL 子查询进行统计

php - 将值插入 SQL 下拉列表中的变量

mysql - 如何使用同一列中的数据创建 SQL View 作为单独的行?

java - 应用程序 -> 数据库调用有多昂贵? (即 Java JDBC -> Oracle)?

计算列小计的 SQL 查询

mysql - 如何在排除其他内容的同时查询表中的内容