T-SQL中一组时差的总和?

时间:2018-11-04 13:04:49

标签: sql sql-server tsql

我想总结所有时间差,以显示总工作时间。

select 
    aaaa
from 
    employee B 
inner join 
    (select 
         s.emp_reader_id,
         Sum(case  when  s.in_time is not null and s.out_time is not null  and s.shift_type_id=5 and  LOWER(DATENAME(dw, [att_date]))='friday'then   
cast(datediff(minute,'00:00:00', '23:59:59') / 60 +
     (datediff(minute,'00:00:00', '23:59:59') % 60 / 100.0) as decimal(7, 4)
           ) end) as aaaa
     from 
         Daily_attendance_data s 
     left outer join 
         employee bb on s.emp_reader_id = bb.emp_reader_id
     where 
         att_date between '2018-10-01' and '2018-10-31' 
         and s.emp_reader_id = 1039
     group by 
         s.emp_reader_id) A on B.emp_reader_id = A.emp_reader_id 

当前输出:

aaaa
47.1800

它提供了按小时列出的时间列表,但是我想将其总计为一个总计。

总计

样本数据:

23:59
23:59

预期输出:

47.58

2 个答案:

答案 0 :(得分:3)

我认为您应该将所有时间都转换为秒,计算总和,然后将总数转换为HH:mm:ss

  1. 计算秒的总和

    DECLARE @TimeinSecond as integer = 0
    
    select @TimeinSecond = Sum(DATEDIFF(SECOND, '0:00:00', [WorkHrs]))
    from Daily_attendance_data 
    
  2. 转换HH:mm:ss格式

    SELECT RIGHT('0' + CAST(@TimeinSecond / 3600 AS VARCHAR),2) + ':' +
    RIGHT('0' + CAST((@TimeinSecond / 60) % 60 AS VARCHAR),2) + ':' +
    RIGHT('0' + CAST(@TimeinSecond % 60 AS VARCHAR),2)
    

参考

答案 1 :(得分:2)

如果您的日期类型为DateTime。

您可以尝试让您的价值分成两部分。

  1. hours获得价值需要考虑几分钟的时间,SUM(intpart) + SUM(floatpart) / 60
  2. minutesSUM(floatpart) % 60获得价值

看起来像这样。

SELECT concat(SUM(intpart) + SUM(floatpart) / 60,':', SUM(floatpart) % 60)
FROM (
    SELECT cast(SUBSTRING (cast(col as varchar),0,3) as int) intpart,
           cast(SUBSTRING (cast(col as varchar),CHARINDEX(':',col) +1,2)as int) floatpart
    FROM T
) t1

sqlfiddle