SQL如何以HH:MM:SS格式添加两个日期

时间:2014-11-01 06:51:43

标签: sql sql-server date datetime

我试图计算每天上午和下午两班的总工作时间。早班的列是TimeIN和BreakOut,下午是BreakIN和TimeOut,但我没有得到总工作时间。

TIA。任何帮助将不胜感激。

declare @timein datetime ='2014-10-29 07:40:14.000'
,@breakout datetime = '2014-10-29 12:05:11.000'
,@breakin datetime ='2014-10-29 15:06:14.000'
,@timeout datetime ='2014-10-29 19:05:09.000'
,@totAM int, @totPM int , @totWorkHrs datetime

set @totAM = DATEDIFF ( second , @timein , @breakout )
set @totPM = DATEDIFF ( second , @breakin , @timeout )
set @totWorkHrs = @totAM + @totPM

Result:
@totAM = 15897
@totPM = 14335
@totWorkHrs = 30232

Output:
08:39:xx

2 个答案:

答案 0 :(得分:0)

可能你看起来像这样:

declare @timein datetime ='2014-10-29 07:40:14.000'
,@breakout datetime = '2014-10-29 12:05:11.000'
,@breakin datetime ='2014-10-29 15:06:14.000'
,@timeout datetime ='2014-10-29 19:05:09.000'
,@totAM int, @totPM int , @totWorkHrs datetime

set @totAM = DATEDIFF ( second , @timein , @breakout )
set @totPM = DATEDIFF ( second , @breakin , @timeout )




SELECT CONVERT(VARCHAR(10),@totAM/3600)  
    +':' 
    + RIGHT('00'+CONVERT(VARCHAR(2),(@totAM%3600)/60),2) 
    +':' 
    + RIGHT('00'+CONVERT(VARCHAR(2),@totAM%60),2)as TOTAM 


SELECT CONVERT(VARCHAR(10),@totPM/3600)  
    +':' 
    + RIGHT('00'+CONVERT(VARCHAR(2),(@totAM%3600)/60),2) 
    +':' 
    + RIGHT('00'+CONVERT(VARCHAR(2),@totAM%60),2)as TOTPM 

OUTPUT

TOTAM
4:24:57

TOTPM
3:24:57

修改

SELECT CONVERT(VARCHAR(10),(@totAM+@totPM)/3600)  
    +':' 
    + RIGHT('00'+CONVERT(VARCHAR(2),((@totAM+@totPM)%3600)/60),2) 
    +':' 
    + RIGHT('00'+CONVERT(VARCHAR(2),(@totAM+@totPM)%60),2)as TotalTime 

TotalTime
8:23:52

答案 1 :(得分:0)

从上午到下午的总工作时间

declare @timein datetime ='2014-10-29 07:40:14.000'
,@breakout datetime = '2014-10-29 12:05:11.000'
,@breakin datetime ='2014-10-29 15:06:14.000'
,@timeout datetime ='2014-10-29 19:05:09.000'
,@totAM int, @totPM int, @totHrs int, @totMins int, @totSecs int, @totAMPM int , @totWorkHrs datetime

set @totAM = DATEDIFF ( second , @timein , @breakout )

set @totPM = DATEDIFF ( second , @breakin , @timeout )

SET @totAMPM = (@totPM+ @totAM)

SET @totHrs = @totAMPM/3600
SET @totMins = (@totAMPM % 3600) / 60
SET @totSecs = @totAMPM % 60


Select @totHrs as Hours, @totMins as minutes,  @totSecs  as Seconds