2015-08-03 49 views
1

之间我的数据是这样的:DATEDIFF小时

Col1  Col2  output 
09:35 16:00 6,25 <-- need help with this 

我想有输出显示H,m(小时,分钟再予)

Datediff(Hours,Col1,Col2) 

给我7

我不如果可能,只要使用一些简单的函数就不想制作任何参数。

+0

你为什么要这样的格式?时间格式会不会好得多?您试图从时间中减去时间以获得新时间,然后使用格式进行操作,而不是保留时间格式。 –

回答

2

我想,我只想做明确,通过采取以分钟为单位的差异,做数值计算:

select (cast(datediff(minute, col1, col2)/60 as varchar(255)) + ',' + 
     right('00' + cast(datediff(minute, col1, col2) % 60 as varchar(255)), 2) 
     ) 
0

你可以尝试以下方法解决:

输出的 Solution 1
-- Solution 1: Mathematical correct time 
CREATE TABLE #time(col1 time, col2 time) 

INSERT INTO #time(col1, col2) 
VALUES(N'09:35',N'16:00'),(N'8:10',N'22:44') 

SELECT col1, col2, CONVERT(decimal(10,2),DATEDIFF(MINUTE,Col1,Col2))/60 as [output] 
FROM #time 

DROP TABLE #time 
GO 

-- Solution 2: Your expected value 
CREATE TABLE #time(col1 time, col2 time) 

INSERT INTO #time(col1, col2) 
VALUES(N'09:35',N'16:00'),(N'8:10',N'22:44') 

SELECT DATEDIFF(MINUTE,Col1,Col2)/60 as [hours], DATEDIFF(MINUTE,Col1,Col2)%60 as [minutes], 
    -- Contated values: 
    DATEDIFF(MINUTE,Col1,Col2)/60 + (CONVERT(decimal(10,2),DATEDIFF(MINUTE,Col1,Col2)%60))/100 as [output] 
FROM #time 

DROP TABLE #time 

输出 Solution 2
col1    col2    output 
---------------- ---------------- --------------------------------------- 
09:35:00.0000000 16:00:00.0000000 6.416666 
08:10:00.0000000 22:44:00.0000000 14.566666 

hours  minutes  output 
----------- ----------- --------------------------------------- 
6   25   6.250000 
14   34   14.340000 

,您仍然可以圆/转换价值以匹配您的2位数字模式 - 如果需要的话。

3

什么让以分钟为单位的日期diff和结果转换到你想要的字符串:

SELECT CONCAT(DATEDIFF(MINUTE, '09:35', '16:00')/60, ':', DATEDIFF(MINUTE, '09:35', '16:00') % 60); 
0

请注意,如果第二次col1时间大于col2时间,您将得到一个时髦结果。

通过简单的铸造两次为datetime,你可以减去他们:

SELECT 
    cast(cast('16:00' as datetime) - cast('09:35' as datetime) as time(0)) 

结果:

06:25:00 

万一你一个类似的格式(我宁愿时间格式):

SELECT 
    stuff(left(cast(cast('16:00' as datetime) 
    - cast('09:35' as datetime) as time(0)), 5), 3,1,',') 

结果:

06,25