如何使用sql time数据类型获取每周活动的小时数?

时间:2018-04-20 03:32:18

标签: sql-server

希望有人可以帮助我。我试图生成一份报告,每周列出每个部门每个活动的所有工作时间。

我的表包含以下信息

enter image description here

我想完成以下

enter image description here

我一直在尝试创建一个查询,这是我到目前为止所做的。

select id, Departmentname, Week, Activity, 
substring(cast(convert(Time, dateadd(millisecond, sum(datediff(millisecond, 
0, cast([Time] as datetime))), 0), 108) as CHAR(5)),0,9) AS 'Time'
from Time where Week LIKE '%' AND Departmentname LIKE '%' GROUP BY Week, 
Activity, Departmentname, id

1 个答案:

答案 0 :(得分:1)

看起来你只需要分组。只需要将时间转换为int来计算总数

select
    [Week], Dept, Activity
    , [time] = isnull(right('0' + cast(total / 60 as varchar(2)), 2) + ':' + right('0' + cast(total % 60 as varchar(2)), 2), '00:00')
from (
    select
        [Week], Dept, Activity
        , total = sum(cast(left([time], 2) as int) * 60 + cast(right([time], 2) as int))
    from
        myTable
    group by [Week], Dept, Activity
) t