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 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 这样的输出

4

5 回答 5

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)))

请参阅带有演示的 SQL Fiddle

于 2012-08-07T10:53:59.897 回答
0

为什么不使用此页面中的日期或时间类型http://msdn.microsoft.com/en-us/library/ms186724.aspx

然后,您可能只想以仅需要小时和分钟的格式打印结果。

于 2012-08-07T10:29:04.887 回答
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))
于 2012-08-07T10:32:12.507 回答
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
于 2012-08-07T10:36:53.827 回答
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)))
于 2012-08-07T10:52:29.620 回答