sql - Calculation of balance after each transaction -
i have table this:
cust_id acc_no trans_id trans_type amount 1111 1001 10 credit 2000.0 1111 1001 11 credit 1000.0 1111 1001 12 debit 1000.0 2222 1002 13 credit 2000.0 2222 1002 14 debit 1000.0
i want hive query or sql query every transaction done customer balance should calculated so.
i want output follows:
cust_id acc_no trans_id trans_type amount balance 1111.0 1001.0 10.0 credit 2000.0 2000.0 1111.0 1001.0 11.0 credit 1000.0 3000.0 1111.0 1001.0 12.0 debit 1000.0 2000.0 2222.0 1002.0 13.0 credit 2000.0 2000.0 2222.0 1002.0 14.0 debit 1000.0 1000.0
i've tried
select * (select cust_id, acc_no, trans_id, trans_type, amount, case when trim(trans_type) = 'credit' ball = trim(bal) + trim(amt) else ball = trim(bal) - trim(amt) end ban) l;
this query trick :
select t1.cust_id,t1.acc_no,t1.trans_id,t1.trans_type,t1.amount, sum(t2.amount*case when t2.trans_type = 'credit' 1 else -1 end) balance table1 t1 inner join table1 t2 on t1.cust_id = t2.cust_id , t1.acc_no = t2.acc_no , t1.trans_id >= t2.trans_id group t1.cust_id,t1.acc_no,t1.trans_id,t1.trans_type,t1.amount
see sqlfiddle : http://www.sqlfiddle.com/#!2/3b5d8/15/0
edit : sql fiddle
mysql 5.5.32 schema setup:
create table table1 (`cust_id` int, `acc_no` int, `trans_id` int, `trans_type` varchar(6), `amount` int) ; insert table1 (`cust_id`, `acc_no`, `trans_id`, `trans_type`, `amount`) values (1111, 1001, 10, 'credit', 2000.0), (1111, 1001, 11, 'credit', 1000.0), (1111, 1001, 12, 'debit', 1000.0), (2222, 1002, 13, 'credit', 2000.0), (2222, 1002, 14, 'debit', 1000.0) ;
query 1:
select t1.cust_id,t1.acc_no,t1.trans_id,t1.trans_type,t1.amount, sum(t2.amount*case when t2.trans_type = 'credit' 1 else -1 end) balance table1 t1 inner join table1 t2 on t1.cust_id = t2.cust_id , t1.acc_no = t2.acc_no , t1.trans_id >= t2.trans_id group t1.cust_id,t1.acc_no,t1.trans_id,t1.trans_type,t1.amount
| cust_id | acc_no | trans_id | trans_type | amount | balance | |---------|--------|----------|------------|--------|---------| | 1111 | 1001 | 10 | credit | 2000 | 2000 | | 1111 | 1001 | 11 | credit | 1000 | 3000 | | 1111 | 1001 | 12 | debit | 1000 | 2000 | | 2222 | 1002 | 13 | credit | 2000 | 2000 | | 2222 | 1002 | 14 | debit | 1000 | 1000 |
Comments
Post a Comment