我的数据如下:
Col1 Col2 output
09:35 16:00 6,25 <-- need help with this
我希望输出显示H,m
(小时,小时)
Datediff(Hours,Col1,Col2)
给我7。
如果可能,我不想制作任何参数只使用一些简单的函数。
答案 0 :(得分:3)
如何以分钟为单位获取日期差异并将结果转换为所需的字符串:
SELECT CONCAT(DATEDIFF(MINUTE, '09:35', '16:00') / 60, ':', DATEDIFF(MINUTE, '09:35', '16:00') % 60 );
答案 1 :(得分:2)
我想我会明确地做到这一点,通过在几分钟内取得差异并进行数值计算:
select (cast(datediff(minute, col1, col2) / 60 as varchar(255)) + ',' +
right('00' + cast(datediff(minute, col1, col2) % 60 as varchar(255)), 2)
)
答案 2 :(得分:0)
您可以尝试以下解决方案之一:
-- 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 1
的输出:
col1 col2 output
---------------- ---------------- ---------------------------------------
09:35:00.0000000 16:00:00.0000000 6.416666
08:10:00.0000000 22:44:00.0000000 14.566666
Solution 2
的输出:
hours minutes output
----------- ----------- ---------------------------------------
6 25 6.250000
14 34 14.340000
如果需要,您仍然可以对值进行舍入/转换以匹配您的2位数字模式。
答案 3 :(得分:0)
请注意,如果第二个col1时间大于col2时间,您将获得一个时髦的结果。
通过简单地将两次转换为日期时间,您可以减去它们:
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