Dad*_*Pvg 7 sql t-sql sql-server
我在查找存储在列中的值的总和时遇到问题,
我有这样一张桌子:
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
.
.
.
Run Code Online (Sandbox Code Playgroud)
我需要找到的是Sum(total_hours)小组gs_cycle_no.但是该Sum方法不适用于varchar列,并且由于其格式,我也无法将其转换为十进制,
我怎样才能找到基于sum的total_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
Run Code Online (Sandbox Code Playgroud)
如果你不这样做,试试这个:
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
375 次 |
| 最近记录: |