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

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

希望大牛们指教,谢谢!

还有不用游标如何循环一个表的记录去累加?
sql问题

------解决方案--------------------
数学没有学好吧,你的公式不就是最后一条减去低一天条的结果吗

------解决方案--------------------
select a.milleage - b.milleage as summilleage
from table1 a ,table1 b
where not exists (
select 1 from table1 where gpstime > a.gpstime
)
and not exists (
select 1 from table1 where gpstime < b.gpstime
)

------解决方案--------------------
你这个直接就是最后一条减第一条记录嘛.
你做个数学的公式就知道了.中间的项都被中和了
------解决方案--------------------
引用:
关键不是递增的


按照时间升序排列

可能文字难以说清楚,举例来说明吧

------解决方案--------------------
一楼回复的很对,中间项目向抵消,只剩最后一个和第一个的运算!
------解决方案--------------------
怎么算出来的?能解释一下么。
------解决方案--------------------
数学问题
(A2-A1)+(A3-A2)+……+(An-An-1)
=-A1+(A2-A2)+(A3-A3)+……+(An-1-An-1)+An
=An-A1
------解决方案--------------------
29-12=17
------解决方案--------------------
神啊,我的问题我都写不出来了
------解决方案--------------------
;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