如何在SQL Server 2008中获取时间字段的总和

我在查找存储在列中的值的总和时遇到问题,

我有这样一张桌子:

gs_cycle_no    | from_time   | to_time  | total_hours(varchar) ...
GSC-334/2012   | 13:00       | 7:00     |  42:00
GSC-334/2012   | 8:30        | 3:45     |  6:00
.
.
.

我需要找到的是由gs_cycle_no组成的Sum(total_hours)组.
但Sum方法不能在varchar列上工作,并且由于其格式,我也无法将其转换为十进制,

如何根据gs_cycle_no找到total_hours列的总和?

解决方法

如果你没有分钟而且只有几个小时,那么你可以这样做:
select
    cast(sum(cast(replace(total_hours,':','') as int) / 100) as nvarchar(max)) + ':00'
from Table1
group by gs_cycle_no

如果你不这样做,试试这个:

with cte as
(
    select
        gs_cycle_no,sum(cast(left(total_hours,len(total_hours) - 3) as int)) as h,sum(cast(right(total_hours,2) as int)) as m
    from Table1
    group by gs_cycle_no
)
select
    gs_cycle_no,cast(h + m / 60 as nvarchar(max)) + ':' +
    right('00' + cast(m % 60 as nvarchar(max)),2)
from cte

sql fiddle demo

相关文章

SELECT a.*,b.dp_name,c.pa_name,fm_name=(CASE WHEN a.fm_n...
if not exists(select name from syscolumns where name=&am...
select a.*,pano=a.pa_no,b.pa_name,f.dp_name,e.fw_state_n...
要在 SQL Server 2019 中设置定时自动重启,可以使用 Window...
您收到的错误消息表明数据库 'EastRiver' 的...
首先我需要查询出需要使用SQL Server Profiler跟踪的数据库标...