在SQL Server中执行日期/时间减法

时间:2012-03-14 23:31:28

标签: sql sql-server sql-server-2008

我在表格中有四个字段:

date entered, time entered, date completed, time completed

我想知道日期/时间ENTERED和日期/时间COMPLETED之间的区别

例如

date entered = 1/1/2001
time entered = 10:00
time completed = 1/2/2001
time completed = 11:00

差异是25小时。

如何使用select语句执行此计算?

我刚试过这个:

DATEDIFF(hh,dateadd(hh,[Time Entered],[Date Entered]),dateadd(hh,[Time Completed],[Date Completed]) ) AS [Hours]

并收到以下错误:

Msg 8116, Level 16, State 1, Line 2
Argument data type time is invalid for argument 2 of dateadd function.

5 个答案:

答案 0 :(得分:5)

Declare @dateentered date = '20010101'
Declare @timeentered time = '10:00' 
Declare @datecompleted date = '20010102' 
Declare @timecompleted time = '11:00'

select datediff(hh, @dateentered + cast(@timeentered as datetime), 
                    @datecompleted + cast(@timecompleted as datetime))

因此,就表格的列而言:

select datediff(hh, [date entered] + cast([time entered] as datetime), 
                    [date completed] + cast([time completed] as datetime)) as [Hours]

答案 1 :(得分:3)

select datediff(hour,'1/1/2001 10:00','1/2/2001 11:00')

答案 2 :(得分:1)

使用DateDiff

答案 3 :(得分:1)

尝试

select DateDiff(ss, [Date Entered] + convert(datetime, [Time Entered]), 
                    [Date Completed] + convert(datetime, [Time Completed])) 
from myTable

以秒为单位获得结果。

这是一个独立的例子:

declare @dateentered date = '1/1/2001'
declare @timeentered time = '10:00'
declare @datecompleted date = '1/2/2001'
declare @timecompleted time = '11:00'

select DateDiff(ss, 
    @dateentered + convert(datetime, @timeentered), 
    @datecompleted + convert(datetime, @timecompleted)) 

当然,您可以为DATEDIFF指定不同的 dateparts

答案 4 :(得分:0)

DECLARE @StartDate DATETIME
Declare @EndDate DATETIME
declare @startime datetime
declare @endime datetime

SET @StartDate = '2001-01-01'
set @startime = '10:00'
SET @EndDate = '2001-01-02'
set @endime = '11:00'

set @StartDate = @StartDate + @startime
set @EndDate = @EndDate + @endime

--To get only Hours
SELECT DATEDIFF(hh, @StartDate,@EndDate ) AS [Hours];