Sql server 2005 在SQLServer2005中不使用while循环更新表数据
在sql中,我有如下表数据Sql server 2005 在SQLServer2005中不使用while循环更新表数据,sql-server-2005,select,Sql Server 2005,Select,在sql中,我有如下表数据 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
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
我想在下面的select语句中获取数据
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
等等
这意味着每种类型都必须有基于金额类型的当前总金额
而且它需要是不具有while循环的,因为执行它需要很长时间
for eg:
in type 1
ID Amount current
1 2000-add 2000
2 1000-sub 1000
3 2000-add 3000
4 1000-add 4000
如何做到这一点自连接就足够了:
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
:
解释
您不能使用函数,因为您不是为具有相同值的所有行聚合,而是为具有相同值的前几行聚合。然后,您需要对同一个表进行非等联接,将前面所有行t1.id>=t2.id的值相同的t1.type=t2.type联接起来。我认为这个查询可以工作:
选择id、类型、金额,从mytable t1中选择sumamount,其中t1.type=t2.type和t1.id既然您已经更改了输入规范,那么您是否也可以更新您的预期结果表?现在我在@Damien_不相信的情况下更正了它欢迎使用StackOverflow,现在问题->新帖子我还有一个疑问,现在需要编辑问题@danhip抱歉我所做的,但我在问题中提到的上述结果是我想要……@danhip你的答案是可以的,但我想要上面这样的输出@rahullanjan这是一个相关查询,为了提高性能,你应该避免:
| 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 |