在SQL中减去小时数

时间:2017-06-27 07:23:34

标签: sql sql-server tsql

我在DB中有几个小时(06:42,9:30,..)。我想从08:00减去小时数

我尝试了以下查询

Select totalhrsinside as hour,convert(varchar, dateadd(minute, -8, totalhrsinside), 100) as diff from table_name

但它没有按预期工作

输出

hour    diff
06:42   -01:18 
09:30   01:30 

2 个答案:

答案 0 :(得分:5)

我认为您正在寻找时间上的差异,而不是减去或添加。

SELECT  Hours
,       CONCAT(
                    CASE WHEN SIGN(diff) = -1 THEN '-' END
                  , FORMAT(ABS(diff/60), '0#')
                  , ':'
                  , FORMAT(ABS(diff%60), '0#')
              ) diff
FROM    (
            SELECT  '6:42' Hours, DATEDIFF(MINUTE, '8:00', '6:42') diff UNION ALL
            SELECT  '9:30' Hours, DATEDIFF(MINUTE, '8:00', '9:30') diff 
        ) D

结果:

+-------+-------+
| Hours | diff  |
+-------+-------+
| 6:42  | -01:18 |
| 9:30  | 01:30  |
+-------+-------+

答案 1 :(得分:1)

如果时间较短,请使用案例添加减号。

select 
totalhrsinside as [hour],  
concat(
  case when DateDiff(minute, '08:00', totalhrsinside) < 0 then '-' end, 
  left(dateadd(minute, abs(datediff(minute, '08:00', totalhrsinside)), cast('00:00' as time)), 5)
) as diff
from 
(
 select totalhrsinside 
 from (values 
 ('06:45'),
 ('08:00'),
 ('09:30')
 ) v(totalhrsinside)
) testvalues;

返回:

06:45   -01:15
08:00   00:00
09:30   01:30