在线咨询
QQ咨询
服务热线
服务热线:13125520620
TOP

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

发布时间:2011-11-12 浏览:4722

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

表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
==结果
==结果
1 0007 2005-01-01 00:00:00.000 80.299999999999997 80.299999999999997 
2 0007 2005-01-01 00:00:00.000 20.199999999999999 100.5 
3 0008 2005-01-06 00:00:00.000 10.5                                111.0 

==解决方案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
==结果
1 0007 2005-01-01 00:00:00.000 80.299999999999997 80.299999999999997 
2 0007 2005-01-01 00:00:00.000 20.199999999999999 100.5 
3 0008 2005-01-06 00:00:00.000 10.5                                111.0 

TAG
软件定制,软件开发,瀚森HANSEN
0
该内容对我有帮助