【问题标题】:sql query adding previous value to next value [duplicate]sql查询将前一个值添加到下一个值[重复]
【发布时间】:2014-08-29 05:28:35
【问题描述】:

我想添加我的表的两列值例如:

 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

【问题讨论】:

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


【解决方案1】:

Mohan,请参阅下面的答案,它应该对您有所帮助。 将@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

结果:

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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-01
  • 2016-04-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多