我想得到超时列的总结我得到的

时间:2017-05-10 12:06:39

标签: sql-server

 declare @system_name varchar;
WITH temp AS (
---get overtime of single date------
select Work_Date , max(DATEADD(ss,(datediff(ss,'6:45 PM',Work_EndTime )),CAST('00:00:00' AS TIME))) as OverTime
from tblWorkTime where Work_Date between Work_StartTime and Work_EndTime and Work_EndTime > '6:45 PM'
AND system_name=@system_name group by Work_Date 
)

-----get sum of overtime of particuler 
Select cast(dateadd(millisecond,sum(datediff
(millisecond,0,cast(OverTime as datetime))),0) as time) as Overtime from temp 

1 个答案:

答案 0 :(得分:0)

我对架构做了一些假设并稍微修改了你的sql。我还在数小时,分钟和秒钟内返回数据,以避免重复数据。如果你修改代码,我相信它会做你想做的。

CREATE TABLE #tblWorkTime ( system_name     VARCHAR(50)
                          , Work_Date       DATE
                          , Work_StartTime  TIME
                          , Work_EndTime    TIME )

INSERT INTO #tblWorkTime (system_name, Work_Date, Work_StartTime, Work_EndTime)  
  VALUES ( 'Foo', '20170101' , '09:00:00', '18:50:00.000')
       , ( 'Foo', '20170101' , '09:00:00', '19:50:00.000')

DECLARE @system_name VARCHAR(50) = 'Foo'

; WITH CTE AS (
    SELECT  Work_Date 
          , OverTimeHours       = DATEDIFF( SECOND,'18:45', Work_EndTime ) / 60 / 60
          , OverTimeMinutes     = DATEDIFF( SECOND,'18:45', Work_EndTime ) / 60 % 60
          , OverTimeSeconds     = DATEDIFF( SECOND,'18:45', Work_EndTime ) % 60 % 60         
    FROM    #tblWorkTime 
    WHERE   Work_EndTime >  '6:45 PM' 
      AND   system_name  =  @system_name 
)
SELECT  Work_Date
      , Hours   = SUM(OverTimeHours)
      , Minutes = SUM(OverTimeMinutes)
      , Seconds = SUM(OverTimeSeconds)
FROM    CTE
GROUP BY Work_Date