繁体   English   中英

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

[英]How to get sum of time field in 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
.
.
.

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

我怎样才能找到sumtotal_hours列,基于gs_cycle_no

如果你没有分钟而且只有几个小时,那么你可以这样做:

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小提琴演示

这将有效:

;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

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

SQLFiddle演示

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM