您的位置:首页 > 数据库

数据统计例子,相关子查询!(SQL 中循环操作一列数据方法)

2011-01-12 14:22 726 查看
问题:
数据及需要实现的累计值--即每次“发货数量”与上次发货的“累计”值相加后再放入一张表中体现出来

表A
_______________________________________
| ID 提单号 提货日期 实发数量 累计|
|--------------------------------------|
| 1    0007   2005-01-1  80.3     80.3| 
|  2    0007   2005-01-1  20.2    100.5|  /*  80.3+20.2=100.5
|  3    0008   2005-01-6  10.5      111|    /*  100.5+10.5=111
---------------------------------------+

解决方案1:
--数据装载
declare @Table  table (id int identity(1,1),提货号 varchar(4),提货日期 datetime,实发数量 float)
insert @table select '0007','2005-01-1',80.3
union all  select '0007','2005-01-1',20.2
union all  select '0008','2005-01-6',10.5
==测试
select *,累计=(select sum(实发数量) from @Table where id<=a.id)
from @Table a

--解决方案2: 游标
--数据装载
declare @tab table (ID int,单号 varchar(20),提货日期 datetime,实发数量 decimal(8,1))
insert @tab
values(1,'0007','2005-01-01',80.3)
insert @tab
values(2,'0007','2005-01-01',20.2)
insert @tab
values(3,'0008','2005-01-06',10.5)

==测试
declare @tab1 table (ID int,单号 varchar(20),提货日期 datetime,实发数量 decimal(8,1),累计 decimal(8,1))

declare @ID int
declare @单号 varchar(20)
declare @提货日期 datetime
declare @实发数量 decimal(8,1)
declare @累计 decimal(8,1)
set @累计=0
declare Num_Cursor CURSOR FOR
select * from @tab
open Num_Cursor
fetch next from Num_Cursor into @ID,@单号,@提货日期,@实发数量
while @@FETCH_STATUS=0
begin
 set @累计=@累计+@实发数量
 insert @tab1
 values(@ID,@单号,@提货日期,@实发数量,@累计)
fetch next  from Num_Cursor  into  @ID,@单号,@提货日期,@实发数量
end
close Num_Cursor
deallocate Num_Cursor

select * from @tab1

 

本文来自CSDN博客http://blog.csdn.net/zlp321002/archive/2005/06/13/393395.aspx
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  sql insert table 测试 float