7

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

我有一张这样的桌子:

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)group by gs_cycle_no。但是该Sum方法不适用于 varchar 列,并且由于其格式,我也无法将其转换为十进制,

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

4

4 回答 4

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

于 2013-08-14T06:45:30.867 回答
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
于 2013-08-14T06:55:55.310 回答
0

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

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
于 2013-08-14T06:48:42.027 回答
0

这是一个解决方案,我将 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
于 2013-08-14T06:49:31.283 回答