首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

关于sql 循环求和有关问题

2013-02-15 
关于sql 循环求和问题我有一张表table1 (milleage,gpstime) 表是按照时间升序排列的,现在想获取milleage总

关于sql 循环求和问题
我有一张表
table1 (milleage,gpstime) 表是按照时间升序排列的,现在想获取milleage总和,
总和=(第2条记录的milleage-第1条记录的milleage)+(第3条记录的milleage-第2条记录的milleage)....

希望大牛们指教,谢谢!

还有不用游标如何循环一个表的记录去累加?
[解决办法]
29-12=17
[解决办法]
神啊,我的问题我都写不出来了关于sql 循环求和有关问题
[解决办法]
;with cte as (
select ROW_NUMBER() OVER (ORDER BY gpstime) AS Row, abc,gpstime from Table_test
)
select sum(b.abc - a.abc)
from cte a,cte b
where a.row = b.row -1
and b.abc > a.abc 
and b.abc < a.abc + 10

[解决办法]
select (select top 1 abc from tb order by gpstime desc)-(select top 1 abc from tb)
[解决办法]
模拟你的数据和脚本


--建表
create table table_Test(abc int,gpstime datetime)
insert into table_Test values (12,'20130128')
insert into table_Test values (15,'20130129')
insert into table_Test values (14,'20130130')
insert into table_Test values (25,'20130131')
insert into table_Test values (29,'20130201')
--你的脚本
select sum((b.abc-a.abc )) as abc   
from (select ROW_NUMBER() OVER (ORDER BY gpstime) AS Row, abc,gpstime 
from Table_test )a  
join (select t.Row,abc,gpstime 
from (select ROW_NUMBER() OVER (ORDER BY gpstime) AS Row, abc,gpstime 
from Table_test )t 
where t.Row>1)b 
 on  a.Row = b.row-1


--结果
abc
-----------
17

(1 row(s) affected)


结果还是17 最后一项减第一项  可能我没太明白你时间的递增是怎么算的 不行你可以用整数代替

PS你的脚本 b表子查询多嵌套一层是多余的 因为on条件已经限制死了 b子查询完全可以和a一样

热点排行