首页 新闻 会员 周边

数据库数值累加查询

0
悬赏园豆:50 [已解决问题] 解决于 2010-06-29 12:53

我有一张表

ID price

1  5

2  10

3  8

7  9

我现在想累加查询出price的值,这个应该怎样写

正确结果为:

prices

5    --第一个价格的值

15   --第一个价格和第二个价格的累加值

23   --第一个价格和第二个第三个价格的累加值

32 --所有价格的累加值,

请问要实现这样的功能应该怎样编写SQL语句,谢谢

R的主页 R | 初学一级 | 园豆:40
提问于:2010-06-29 09:45
< >
分享
最佳答案
0

IF NOT OBJECT_ID('[Testprice2010]') IS NULL
DROP TABLE [Testprice2010]
GO
CREATE TABLE [Testprice2010]
(
[ID] int,
[Price] float null
)
go

INSERT [Testprice2010]
SELECT 1,5 union all
SELECT 2,10 union all
SELECT 3,8 union all
SELECT 7,9
go


select ID as maxID,
(
select sum([Price]) from Testprice2010 where ID<=p.[ID]) as TotalPrice
from [Testprice2010] p

drop table [Testprice2010]
go

 

--maxID    TotalPrice
--1    5
--2    15
--3    23
--7    32

收获园豆:50
邀月 | 高人七级 |园豆:25475 | 2010-06-29 10:14
select id,sum(price) over ( order by id ) from [Testprice2010] ;
killkill | 园豆:1192 (小虾三级) | 2010-06-29 21:56
其他回答(4)
0

这些逻辑还是交给程序处理方便一点。

把表查到内存DataTable里,遍历出一个新表,写一个累加静态函数,都是访问内存的DataTable也很快的。

Astar | 园豆:40805 (高人七级) | 2010-06-29 09:51
0

如果要用SQL来做,我只能想到用游标

代码如下:

declare @priceTable table(SumPrice int)
declare @tempPrice int
declare @sumPrice int
set @sumPrice=0
declare priceCur cursor for
select price from test
open priceCur
fetch next from priceCur into @tempPrice --临时保存价格数据
while @@FETCH_STATUS=0
begin
--累加数据并保存到临时表
set @sumPrice=@sumPrice+@tempPrice
insert into @priceTable values(@sumPrice)
fetch next from priceCur into @tempPrice
end
close priceCur
deallocate priceCur
--查询
select * from @priceTable
kyo-yo | 园豆:5587 (大侠五级) | 2010-06-29 10:30
0

Astar的方法比较好, 把数据取出来, 在内存操作比较好, 如果用到游标, 对SQL的资源中用极大. 而且速度慢

风浪 | 园豆:2996 (老鸟四级) | 2010-06-29 11:40
0

将下语句中的table1换成楼主的表名,然后在查询分析其中运行即可.用的办法是拼接字符串

代码
declare @id int
declare @sql nvarchar(
1000)
set @sql=''

declare cs cursor
for
select id
from table1
open cs
fetch next from cs into @id

while(@@fetch_status=0)
begin
set @sql=@sql+'select '+convert(nvarchar,@id)+' id,sum(price) from table1 where id<='+convert(nvarchar,@id)+' union '
fetch next from cs into @id
end

deallocate cs

set @sql=substring(@sql,0,len(@sql)-4)
exec(@sql)

 

Localhost | 园豆:443 (菜鸟二级) | 2010-06-29 11:47
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册