Calculate the SUM of the Column which has Time Dat

2020-03-31 08:41发布

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?

5条回答
forever°为你锁心
2楼-- · 2020-03-31 08:52

24:36 is the same as 00:36(Next day)

查看更多
该账号已被封号
3楼-- · 2020-03-31 09:03

Your query is working fine the results are correct,

24:36 is the time 00:36 for next day.

You can display maximum 24 hrs. You are not using any day thats why every 24 hrs =0 hrs for next day.

Just change the column values and you can see that.

查看更多
劳资没心,怎么记你
4楼-- · 2020-03-31 09:06

TRY THIS.

SELECT 
CONVERT(VARCHAR(MAX),SUM(DATEPART(HH,CAST(YOUR_FIELD AS DATETIME)))+ 
(SUM(DATEPART(MINUTE,CAST(YOUR_FIELD AS DATETIME)))/60) + 
(SUM(DATEPART(MINUTE,CAST(YOUR_FIELD AS DATETIME)))%60 + 
(SUM(DATEPART(SECOND,CAST(YOUR_FIELD AS DATETIME)))/60))/60) + ':' +
RIGHT('00' + CONVERT(VARCHAR(MAX), 
(SUM(DATEPART(MINUTE,CAST(YOUR_FIELD AS DATETIME)))%60+ 
(SUM(DATEPART(SECOND,CAST(YOUR_FIELD AS DATETIME)))/60))%60),2) + ':' +   
RIGHT('00' + CONVERT(VARCHAR(MAX),SUM(DATEPART(SECOND, 
    CAST(YOUR_FIELD AS DATETIME)))%60),2) AS YOUR_FIELD

FROM YOUR_TABLE
查看更多
等我变得足够好
5楼-- · 2020-03-31 09:09

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.

查看更多
Juvenile、少年°
6楼-- · 2020-03-31 09:12

It would be a tad longwinded, but if you wanted to avoid the day rollover but you could split the second TIME into constituent datepart()'s and then add those on? (even display as a varchar if it's necessary to have an hour value greater than 24.

查看更多
登录 后发表回答