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

时间:2013-08-14 06:31:04

标签: sql sql-server tsql

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

我有一张这样的表:

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
.
.
.

我需要找到的是Sum(total_hours) gs_cycle_noSum。 但sum方法不适用于varchar列,而且由于其格式,我也无法将其转换为十进制,

如何根据total_hours找到gs_cycle_no列的{{1}}?

4 个答案:

答案 0 :(得分:5)

如果您没有分钟而且只有几个小时,那么您可以执行以下操作:

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

答案 1 :(得分:1)

这将有效:

;with times as (
    select gs_cycle_no = 'GSC-334/2012', total_hours = '8:35'
    union all SELECT gs_cycle_no = 'GSC-334/2012', '5:00'
    union all SELECT gs_cycle_no = 'GSC-334/2012', '16:50'
    union all SELECT gs_cycle_no = 'GSC-334/2012', '42:00'
    union all SELECT gs_cycle_no = 'GSC-335/2012', '0:00'
    union all SELECT gs_cycle_no = 'GSC-335/2012', '175:52'
    union all SELECT gs_cycle_no = 'GSC-335/2012', '12:25')
SELECT
    gs_cycle_no,
    hrs = sum(mins) / 60 + sum(hrs),
    mins = sum(mins) % 60
FROM 
    TIMES
    cross apply(
        select c = charindex(':', total_hours)
    ) idx
    cross apply(
        select
            hrs = cast(substring(total_hours, 1, c - 1) as int),
            mins = cast(substring(total_hours, c + 1, len(total_hours)) as int)
    ) ext
group by gs_cycle_no
order by gs_cycle_no

答案 2 :(得分:0)

此查询以分钟为单位查找总和:

SQLFiddle demo

select gs_cycle_no,

  SUM(
  CAST(
  ISNULL(
  substring(total_hours,1,CHARINDEX(':',total_hours)-1)
  ,'0') as INT) * 60
   +
   CAST(
   ISNULL(
   substring(total_hours,CHARINDEX(':',total_hours)+1,100)
   ,'0') as INT) 
   ) 
   from t
group by   gs_cycle_no

答案 3 :(得分:0)

这是解决方案,我将varchar分成两小块,小时和分钟,然后从它们中分钟,最后,SUM它们:

SELECT 
    gs_cycle_no, 
    CAST(SUM(
        SUBSTRING(total_hours,0 ,CHARINDEX(':', total_hours)) * 60 +
        SUBSTRING(total_hours, CHARINDEX(':', total_hours) + 1, LEN(total_hours)))  / 60 AS VARCHAR) + ':' + 
    CAST(SUM(
        SUBSTRING(total_hours,0 ,CHARINDEX(':', total_hours)) * 60 +
        SUBSTRING(total_hours, CHARINDEX(':', total_hours) + 1, LEN(total_hours))) % 60 AS VARCHAR)
FROM Table1
GROUP BY gs_cycle_no