How to get sum of time field in SQL server 2008

Dadapeer Pvg

I am facing a problem in finding the sum of values stored in a column,

I have a table like this:

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

What i need to find is the Sum(total_hours) group by gs_cycle_no. But the Sum method will not work on the varchar column and also i cant convert it to decimal due to its format,

How can i find the sum of total_hours column, based on gs_cycle_no?

Roman Pekar

if you have no minutes and only hours, then you can do something like:

select
    cast(sum(cast(replace(total_hours, ':', '') as int) / 100) as nvarchar(max)) + ':00'
from Table1
group by gs_cycle_no

if you don't, try this:

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

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

누적 SUM SQL Server 2008

분류에서Dev

SQL Server 2008 two tables with common dates field how to select by datewise from both tables

분류에서Dev

SQL Server의 SUM (Time (0))

분류에서Dev

SQL Server의 SUM (Time (0))

분류에서Dev

SQL Server 2008 : how to remove char(0)

분류에서Dev

How to insert Khmer text into SQL Server 2008

분류에서Dev

Elasticsearch - How to get sum of field with terms?

분류에서Dev

SQL Server 2008 Get Records where Group Count = 1

분류에서Dev

SQL Server 2008 R2 - How to split my varchar column string and get 3rd index string

분류에서Dev

How can I get an SFTP server running on Windows 2008?

분류에서Dev

how can we change the date format of SQL Server(2008) Database?

분류에서Dev

how to pivot on number of rows in SQL Server 2008+

분류에서Dev

How to display all the days of a month in SQL Server 2008?

분류에서Dev

IBM WORKLIGHT SQL Server 2008

분류에서Dev

SQL Server 2008의 ORDER BY

분류에서Dev

SQL Server 2008 connection error

분류에서Dev

SQL SERVER 2008 Select 문

분류에서Dev

SQL Server 2008-With 절

분류에서Dev

MS-SQL server 2008r2 selecting the time from smalltimedate irrespective of date

분류에서Dev

Sql Server 2008: Conversion failed when converting date and/or time from character string

분류에서Dev

SQL Server SUM (값)

분류에서Dev

Alter table query plan for sql server 2008

분류에서Dev

Creating clients of SQL Server 2008 in same network

분류에서Dev

SQL Server 2008-피벗

분류에서Dev

SQL Server 2008에서 선택

분류에서Dev

Roll Back Sql Server 2008 query

분류에서Dev

Automatic row deletion in SQL Server 2008

분류에서Dev

SQL Server 2008 dbms 및 Visual Studio

분류에서Dev

Access에서 SQL Server 2008로