问题
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
回答1:
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
回答2:
A self join is enough:
select
t1.id, t1.type, t1.amount, sum(t2.amount) as currenttotal
from
t t1 inner join t t2
on t1.id >= t2.id and t1.type = t2.type
group by
t1.id, t1.type, t1.amount
order by t1.id
Test it at sql fiddle:
| ID | TYPE | AMOUNT | CURRENTTOTAL |
--------------------------------------
| 1 | type1 | 2000 | 2000 |
| 2 | type1 | 1000 | 3000 |
| 3 | type2 | 500 | 500 |
| 4 | type3 | 3000 | 3000 |
| 5 | type1 | 2000 | 5000 |
| 6 | type2 | 500 | 1000 |
| 7 | type3 | 5000 | 8000 |
| 8 | type1 | -1000 | 4000 |
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 )
来源:https://stackoverflow.com/questions/17825830/update-table-data-without-using-while-loop-in-sql-server-2005