sql查询求和并插入另一个表

时间:2018-12-06 17:38:56

标签: sql oracle

根据sqlfiddle中定义的架构,我想获取贷项总和-借方总和,然后为每个客户编号插入此表,将另一个表作为客户编号,余额。任何有关如何执行此操作的线索,我在小提琴中尝试了查询,但似乎不起作用

1 个答案:

答案 0 :(得分:1)

您的问题是您在ACCOUNT_TRANSACTIONS表中混淆了ACCOUNT_TYPETRANSACTION_TYPE-在ACCOUNT_TYPE字段中输入了交易类型(贷方,借方),然后将TRANSACTION_TYPE字段中的帐户类型(客户等)。

如果在表定义中切换ACCOUNT_TYPE和TRANSACTION_TYPE字段,则会得到:

create table account_transactions
  (customer_number varchar2(10),
   transaction_type varchar2(10),
   account_type varchar2(10),
   amount number);

insert into account_transactions values('5555','credit','customer',10);
insert into account_transactions values('5555','debit','customer',10);
insert into account_transactions values('5555','debit','other',15);
insert into account_transactions values('5555','credit','mgr',15);

Here's a fiddle with the fields flipped around

正确填写表格

SELECT t1.CUSTOMER_NUMBER, sum(t2.amount - t1.amount) AS balance
  FROM ACCOUNT_TRANSACTIONS t1,
       ACCOUNT_TRANSACTIONS t2
  where t1.CUSTOMER_NUMBER=t2.CUSTOMER_NUMBER and 
        t1.TRANSACTION_TYPE = 'debit' AND
        t2.TRANSACTION_TYPE= 'credit' and
        t1.ACCOUNT_TYPE='customer' and
        t2.ACCOUNT_TYPE='customer'
  GROUP BY t1.CUSTOMER_NUMBER

工作正常。

好运。