日期:2014-05-17  浏览次数:20558 次

如何用SQL语句实现下面效果
原始数据:
id     编号     金额变化
1      001      200
2      001      300
3      001      -150


要通过SQL语句得到下面效果
id     编号     金额变化   结存
1      001      200      200 
2      001      300      500
3      001      -150     350

问如何实现?

------解决方案--------------------

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)
--
----------------------------------------------------------------