SQL:时间字段为char类型

时间:2016-09-14 19:19:35

标签: sql sql-server-2008

我试图将数据从一个数据库中的表移动到另一个数据库中。一切都很顺利,除了从旅行时间字段获取总旅行时间,该旅行时间字段被设置为H:MM格式的char(6)。我需要在给定日期(由会话日期给出)的路线中的每个站点(由发货号码给出)获取行程时间,并将其总计在该路线的新字段中。

以下是我想要做的事情(总结char字段当然不会起作用)

SELECT 
    [session_date], [dispatch_number], [stop_number], 
    [scheduled_arrival], [route_start], [customer_id],
    [distance], [travel_time], [service_time],
    [driver],
    (SELECT SUM([travel_time])
     FROM [exampleDB]
     WHERE [dispatch_number] = [dispatch_number]
       AND [session_date] = [session_date]) AS total_drive_time
FROM 
    [exampleDB]

非常感谢您的帮助,谢谢您的时间。

3 个答案:

答案 0 :(得分:1)

首先,您可以使用窗口函数在没有相关子查询的情况下编写它:

select e.*,
       sum(datediff(minute, '00:00', convert(time, travel_time))) over
           (partition by dispatch_number, session_date
           ) as total_drivetime_min
from exampleDB;

当然,这并不能解决问题 - 即添加varchars。您可以将其转换为时间,然后转换为分钟:

{{1}}

如果分钟足够,那么这就解决了你的问题。

答案 1 :(得分:0)

也许这可能会有所帮助

Select Cast(DateAdd(MS,Sum(DateDiff(MS,'00:00:00.000',Cast([travel_time] as Time))),'00:00:00.000') as Time)
 From  [exampleDB]
 Where [dispatch_number]=[dispatch_number]
   and [session_date]=[session_date]) AS total_drive_time

要查看快速示例,

Declare @YourTable table (TimeString varchar(25))
Insert Into @YourTable values
('6:30'),
('1:30')

Select Cast(DateAdd(MS,Sum(DateDiff(MS,'00:00:00.000',Cast(TimeString as Time))),'00:00:00.000') as Time)
 From @YourTable

返回

08:00:00.0000000

答案 2 :(得分:0)

如果您的结果也需要HH:MM,请尝试使用以下查询。

;WITH cte_1 AS
(
    SELECT [dispatch_number],[session_date], SUM(DATEDIFF(MINUTE, '0:00:00', [travel_time]+':00'))total_drive_timeInMin 
    FROM dbo.[exampleDB] 
    GROUP BY [dispatch_number],[session_date]
)
SELECT e.[session_date]
  ,e.[dispatch_number]
  ,[stop_number]
  ,[scheduled_arrival]
  ,[route_start]
  ,[customer_id]
  ,[distance]
  ,[travel_time]
  ,[service_time]
  ,[driver]
  , RTRIM(total_drive_timeInMin/60) + ':' + RIGHT('0' + RTRIM(total_drive_timeInMin%60),2) total_drive_timeIn
FROM cte_1 c
 JOIN [exampleDB] e ON c.[dispatch_number]=e.[dispatch_number]
    AND c.[session_date]=e.[session_date]