我想在表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
答案 0 :(得分:1)
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可能看起来很冗长,但逻辑很简单。