使用循环和SUM

时间:2016-12-30 21:49:19

标签: sql tsql join

我有一张表(distance_travelled),列为
主键| VehicleName | StartDate |结束|总距离

Table distance_Travelled


另一个名为Idling with table的表 车辆名称|持续时间|时间戳
Idling Table
我已采取措施,但最好的方法是从头开始问问题 我希望输出为下表,列为
VehicleName | StartDate | EndDate | TotalDistance |持续时间(每个startDate和enddate之间的持续时间之和) Final Table

2 个答案:

答案 0 :(得分:1)

有点讨厌,但你明白了:

select
    dt.id,
    dt.VehicleName,
    dt.StartDate,
    dt.EndDate,
    dt.Total_Distance,
    substring(cast(convert(time,dateadd(millisecond,sum(datediff(millisecond,0,cast([Duration] as datetime))),0),108) as varchar),0,9) [Duration],
    case when substring(cast(convert(time,dateadd(millisecond,sum(datediff(millisecond,0,cast([Duration] as datetime))),0),108) as varchar),0,9) is null then 
        'no duration...'
    else
        'sum between ' + convert(varchar, dt.StartDate, 108) + ' and ' + convert(varchar, dt.EndDate, 108)
    end as [Duration]
from
    distance_travelled dt
    left join idling i on 
         dt.vehiclename = i.VehicleName and
         i.TimeStamp between dt.StartDate and dt.EndDate
group by
    dt.id,
    dt.VehicleName,
    dt.StartDate,
    dt.EndDate,
    dt.Total_Distance

答案 1 :(得分:1)

交叉申请可能适合这里。

然而,ID 2(8:15和10:00的总和)得到18:15。也许原始问题中存在拼写错误或错误,或者需要额外的逻辑。

我应该注意,如果它跨越多天,小时数可以超过24小时。

Select A.*
      ,Duration = Format(IsNull(B.Seconds,0)/3600    ,'00')    -- Hours 00 - 99
                 +Format(IsNull(B.Seconds,0)%3600/60,':00')    -- Minutes
                 --+Format(IsNull(B.Seconds,0)%60     ,':00')  -- Seconds
 From  Distance_Travelled A
 Cross Apply (
              Select Seconds = sum(DateDiff(SECOND,'1900-01-01',Duration))
              From   Idling 
              Where  VehicleName = A.VehicleName
                and  TimeStamp between A.StartDate and A.EndDate
       ) B

返回

enter image description here