在SQL Server中获取Exact计算的总小时数和分钟数

时间:2013-10-23 08:42:10

标签: sql-server

美好的一天。我正在使用ms sql server 2005 express和heres我的表结构:

      User  |        Log_Date         |     Log_In_Time         |       Log_Out_Time      |
-----------------------------------------------------------------------------------------
    xxx     | 2013-10-02 23:00:31.623 | 2013-10-02 23:07:31.623 | 2013-10-03 01:08:31.623 |

注意:

LOG_OUT_TIME 10月3日上午1:08 LOG_IN_TIME 10月2日11:00 PM

现在我要添加列: TOTAL

它看起来像这样:

      User  |        Log_Date         |     Log_In_Time         |       Log_Out_Time      | TOTAL  |
---------------------------------------------------------------------------------------------------
    xxx     | 2013-10-02 23:00:31.623 | 2013-10-02 23:07:31.623 | 2013-10-03 01:08:31.623 | 2.08   |

有人知道吗?

提前谢谢!

4 个答案:

答案 0 :(得分:2)

非常简单的方法:

CAST(Log_Out_Time - Log_In_Time AS TIME)

给出:

02:01:00.0000000

修改

确切查询:

DECLARE @ST DATETIME = '2013-10-02 23:07:31.623'
DECLARE @ET DATETIME = '2013-10-03 01:08:31.623'

SELECT CAST(@ET - @ST AS TIME)

答案 1 :(得分:1)

这将有效:

SELECT CAST(DATEDIFF(hour, Log_In_Time, Log_Out_Time) AS varchar) + '.' + 
    CAST(DATEDIFF(mi, Log_In_Time, Log_Out_Time) / (60 * DATEDIFF(hour, Log_In_Time, Log_Out_Time) ) AS varchar)
FROM tableName

我已经分别计算了小时和分钟。

答案 2 :(得分:0)

您可以使用DateDiff @Unknownymous,我会做的是秒比较,将其转换为浮点数并根据需要除以60。这将为您提供分钟,小时等,以达到您所需的精度。

DECLARE @diff float
DECLARE @diffMin float
DECLARE @diffHour float
DECLARE @diffDay float

SELECT @diff = cast(datediff(ss,Log_in_Time,Log_Out_Time) as FLOAT)
SELECT @diffMin = @diff/60
SELECT @diffHour = @diffMin/60
SELECT @diffDay = @diffHour/24

print @diff
print @diffmin
print @diffhour
print @diffday

答案 3 :(得分:0)

select 
cast(datepart(hour,Log_Out_Time - Log_Date) as varchar) + '.' +  
right('00' + cast(datepart(minute,Log_Out_Time - Log_Date) as varchar),2)