日期:2014-05-17 浏览次数:20592 次
if object_id('test',N'U')>0
drop table test
create table test(id int,[编号] varchar(5),[金额变化] int)
insert into test(id,[编号],[金额变化])
select 1,'001',200 union all
select 2,'001',300 union all
select 3,'001',-150
--语句
select a.id,a.[编号],a.[金额变化]
,SUM(b.[金额变化]) as [结存]
from test a left join test b
on a.id>=b.id
group by a.id,a.[编号],a.[金额变化]
--结果
(3 行受影响)
id 编号 金额变化 结存
----------- ----- ----------- -----------
1 001 200 200
2 001 300 500
3 001 -150 350
(3 行受影响)
----------------------------------------------------------------
-- Author :fredrickhu(小F,向高手学习)
-- Date :2013-09-22 17:36:01
-- Verstion:
-- Microsoft SQL Server 2012 - 11.0.2100.60 (X64)
-- Feb 10 2012 19:39:15
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition: Core-based Licensing (64-bit) on Windows NT 6.1 <X64> (Build 7601: Service Pack 1)
--
----------------------------------------------------------------