我有时间十进制格式,我需要得到差异
我试过以下
declare @hours decimal(10,5)
set @hours = 6.25 --6 Hrs and 25 mins
declare @hours1 decimal(10,5)
set @hours1 = 5.45 --5 Hrs and 45 mins
select CONVERT(varchar(10), CONVERT(int, cast(floor(@hours) as char(2)))-CONVERT(int, cast(floor(@hours1) as char(2))))+ '.'+ CONVERT(varchar(10),CONVERT(int, cast(floor(100*(@hours - floor(@hours))) as char(2)))-
CONVERT(int, cast(floor(100*(@hours1 - floor(@hours1))) as char(2))))
对于此示例,输出为1.-20。我需要输出像.40
答案 0 :(得分:1)
您确实应该将时间值存储为日期时间而不是小数。但是,您可以通过以下方式进行转换:
declare @hours decimal(10,2)
set @hours = 6.25 --6 Hrs and 25 mins
declare @hours1 decimal(10,2)
set @hours1 = 5.45 --5 Hrs and 45 mins
declare @hours2 decimal(10,2)
set @hours2 = 9.45 --8 Hrs and 45 mins
declare @hours3 decimal(10,2)
set @hours3 = 7.45 --7 Hrs and 45 mins
select abs(cast(datediff(minute
, cast(replace(@hours, '.', ':') as time)
, cast(replace(@hours1, '.', ':') as time))/100.0 as decimal(10, 2)))
答案 1 :(得分:0)
为什么不使用此页面中的日期或时间类型http://msdn.microsoft.com/en-us/library/ms186724.aspx
然后您可能只想使用只需要小时和分钟的格式打印结果。
答案 2 :(得分:0)
试试这个:
declare @hours decimal(10,5)
set @hours = 6.25 --6 Hrs and 25 mins
declare @hours1 decimal(10,5)
set @hours1 = 5.45 --5 Hrs and 45 mins
select (cast(LEFT(CAST(@hours as varchar),CHARINDEX('.',CAST(@hours as varchar))-1) as int)*60+
cast(left(RIGHT(CAST(@hours as varchar),LEN(CAST(@hours as varchar))-CHARINDEX('.',CAST(@hours as varchar))),2) as int))-
(cast(LEFT(CAST(@hours1 as varchar),CHARINDEX('.',CAST(@hours1 as varchar))-1) as int)*60+
cast(left(RIGHT(CAST(@hours1 as varchar),LEN(CAST(@hours1 as varchar))-CHARINDEX('.',CAST(@hours1 as varchar))),2) as int))
答案 3 :(得分:0)
declare @totalhours decimal(10,5)
declare @totalhours1 decimal(10,5)
set @totalhours = CONVERT(decimal(5,0),@hours) * 60 + (@hours - CONVERT(decimal(5,0),@hours)) * 100
set @totalhours1 = CONVERT(decimal(5,0),@hours1) * 60 + (@hours1 - CONVERT(decimal(5,0),@hours1)) * 100
select (@totalhours - @totalhours1) / 100
答案 4 :(得分:0)
DECLARE
@input1 DECIMAL(10,5), @input2 DECIMAL(10,5), @output DECIMAL(10,5)
SELECT
@input1 = 6.25,
@input2 = 5.45
-- Step 1; convert the inputs to a sensible representation
SELECT
@input1 = FLOOR(@input1) + ((@input1 - FLOOR(@input1)) / CAST(0.6 AS DECIMAL(10,5))),
@input2 = FLOOR(@input2) + ((@input2 - FLOOR(@input2)) / CAST(0.6 AS DECIMAL(10,5)))
-- Step 2; calculate the difference
SELECT
@output = @input1 - @input2
-- Step 3; conver the output back to the original representation
SELECT
@output = FLOOR(@output) + ((@output - FLOOR(@output)) * CAST(0.6 AS DECIMAL(10,5)))