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

怎么用简单的sql语句记流水?
有一个流水表TF,字段有ID,FirstQuantity,ChangeQuantity,FinalQuantity。ID表示物品,后面几个表示期初数量,变化数量,最终数量。
假设表TF现在是空
有一张变动表TC,字段有ID,Quantity。表示某物品的数量。里面会有重复。内容如下:
ID Quantity
1  10
1  20
1  30
那么当我把TC的数据加入到TF后,TF的内容应该如下

ID FirstQuantity ChangeQuantity FinalQuantity
1   0             10              10
1   10            20              30
1   30            30              60

这个功能,用编程的方法很好解决,就是一个一个循环写入,但是效率太慢了。
那么能不能用一条sql语句就搞定呢?

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



create table tc(ID int, Quantity int)

insert into tc
select 1  ,10  union all
select 1  ,20 union all
select 1  ,30 
go

;with t
as
(
select *,
       ROW_NUMBER() over(partition by id order by @@servername) rownum
from tc
)


select ID,
       FirstQuantity,
       ChangeQuantity,
       FirstQuantity+ChangeQuantity as inalQuantity
from 
(
select ID,
       case when rownum = 1 then 0 
            else (select SUM(Quantity) from t t2 
                  where t2.ID = t1.id and t2.rownum < t1.rownum)
       end as FirstQuantity,
       Quantity as ChangeQuantity       
from t t1
)tt
/*
ID FirstQuantity ChangeQuantity inalQuantity
1 0 10 10
1 10 20 30
1 30 30 60
*/