gs79
asked on
Aggregate
I have a data as follows. We have two set of records with different grain as shown below: when we have total amount used amount is blank.
id1 id2 id3 tot_amt used_amt
abc 100
abc 111 001 25
abc 111 002 50
now I need to calculate unused_amt which is difference of tot_amt and used amount (100 - 75) and populate in the same line as tot amt. Here is the output desired
id1 id2 id3 tot_amt used_amt unused_amt
abc 100 25
abc 111 001 25
abc 111 002 50
is there a way to do this? Is there an aggregate function we can use? please help
thanks
id1 id2 id3 tot_amt used_amt
abc 100
abc 111 001 25
abc 111 002 50
now I need to calculate unused_amt which is difference of tot_amt and used amount (100 - 75) and populate in the same line as tot amt. Here is the output desired
id1 id2 id3 tot_amt used_amt unused_amt
abc 100 25
abc 111 001 25
abc 111 002 50
is there a way to do this? Is there an aggregate function we can use? please help
thanks
Check the queries in sql fiddle..
select id1,id2,id3,tot_amt,used_a mt,sum_tot _amt-sum_u nused unused_amt from(
select id1,id2,id3,tot_amt,used_a mt,
sum(tot_amt) over(partition by id1) sum_tot_amt,
sum(used_amt) over(partition by id1) sum_unused from mytable);
If you want to have unused_amout per record then use this
select id1,id2,id3,tot_amt,used_a mt,
sum(tot_amt) over(partition by id1)-nvl(used_amt,0) unused_amt from mytable;
check out both the query and their result sets in sql fiddle
http://www.sqlfiddle.com/#!4/f2142/30
select id1,id2,id3,tot_amt,used_a
select id1,id2,id3,tot_amt,used_a
sum(tot_amt) over(partition by id1) sum_tot_amt,
sum(used_amt) over(partition by id1) sum_unused from mytable);
If you want to have unused_amout per record then use this
select id1,id2,id3,tot_amt,used_a
sum(tot_amt) over(partition by id1)-nvl(used_amt,0) unused_amt from mytable;
check out both the query and their result sets in sql fiddle
http://www.sqlfiddle.com/#!4/f2142/30
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Open in new window