Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
329 views
in Technique[技术] by (71.8m points)

sql - Calculate the SUM of the Column which has Time DataType:

I want to calculate the Sum of the Field which has Time DataType.

My Table is Below:

  TableA:

            TotalTime
          -------------
             12:18:00
             12:18:00

Here I want to sum the two time fields. I tried the below Query

   SELECT CAST(
              DATEADD(MS, SUM(DATEDIFF(MS, '00:00:00.000', 
                CONVERT(TIME, TotalTime))), '00:00:00.000'
               ) AS TOTALTIME) 
    FROM [TableA]

But it gives the Output as

            TOTALTIME
        -----------------
         00:36:00.0000000

But My Desired Output would be like below:

            TOTALTIME
        -----------------
            24:36:00

How to get this Output?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could sum the total number of seconds, or datediff(second,0,datecolumn). You can format that as a time string with some math. For example, the total number of minutes is totalseconds / 60 % 60. For example:

select  cast(sum(datediff(second,0,dt))/3600 as varchar(12)) + ':' + 
        right('0' + cast(sum(datediff(second,0,dt))/60%60 as varchar(2)),2) +
        ':' + right('0' + cast(sum(datediff(second,0,dt))%60 as varchar(2)),2)
from    TestTable

Working code at SQL Fiddle.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...