sql查询将以前的值添加到下一个值

时间:2014-08-29 05:28:36

标签: sql sql-server sql-server-2008 tsql sql-server-2008-r2

我想在表E.g中添加两列值:

 Id Distance    Duration    ETA_Distance    ETA_Duration
 1  0             0           20                60
 2  14           20           NULL              NULL
 3  12           10           NULL              NULL
 4  15           70           NULL              NULL

考虑到上面的表格,我想要一个SQL查询,它给出了如下结果:

 Id Distance    Duration    ETA_Distance    ETA_Duration
 1  0             0           20                60
 2  14           20           34                80
 3  12           10           46                90
 4  15           70           61                160

1 个答案:

答案 0 :(得分:1)

莫汉,看到下面的答案,它应该对你有所帮助。 用表替换@table。 我使用临时表来测试代码。

Declare @tab table (Id int,Distance int,   Duration int,    ETA_Distance int,   ETA_Duration int)
Insert into @tab values 
(1,0 ,  0,20  ,60  ),
(2,14, 20,NULL,NULL),
(3,12, 10,NULL,NULL),
(4,15, 70,NULL,NULL)


Select  X.Id,X.Distance,X.Duration,
        Y.ETA_Distance,Y.ETA_Duration
From    @tab X
Join    (
Select  B.Id,
        Sum(A.Distance) ETA_Distance,
        Sum(A.Duration) ETA_Duration 
From    (Select Id,ISNULL(ETA_Distance,Distance) Distance,ISNULL(ETA_Duration,Duration) Duration From @tab) A,
        (Select Id,ISNULL(ETA_Distance,Distance) Distance,ISNULL(ETA_Duration,Duration) Duration  From @tab) B
Where   A.Id <= B.Id
Group   By B.Id) Y
On      X.Id = Y. Id

结果:

enter image description here

Sql可能看起来很冗长,但逻辑很简单。