in sql i have table data like below
id type amount
1 type1 2000
2 type1 1000
3 type2 500
4 type3 3000
5 type1 2000
6 type2 500
7 type3 5000
8 type1 1000
and i want to get datas in select statement like below
id type amount current
1 type1 2000 2000
2 type1 1000 1000
3 type2 500 500
4 type3 3000 3000
5 type1 2000 3000
6 type2 -500 0
7 type3 5000 2000
8 type1 -1000 4000
and so on that means each type must have its current total amount based on amount type and its need to be dont have while loop because it takes long time to execute
for eg:
in type 1
ID Amount current
1 2000-add 2000
2 1000-sub 1000
3 2000-add 3000
4 1000-add 4000
how to do it
I think this query will work:
select id,type,amount,(select sum(amount) from mytable t1 where t1.type=t2.type and t1.id<=t2.id) currenttotal from mytable t2
A self join is enough:
Test it at sql fiddle:
Explanation
You can not use windowed functions because you don't aggregate for all rows of a same value but for previous rows of same value. Then, you need a non equi join to same table, you get in join all previous rows (
t1.id >= t2.id
) of same value (t1.type = t2.type
)