Calculate the SUM of the Column which has Time DataType:

前端 未结 5 1097
无人及你
无人及你 2021-01-17 04:37

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

My Table is Below:

  TableA:

            TotalTime
          -------------
                


        
相关标签:
5条回答
  • 2021-01-17 05:14

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

    0 讨论(0)
  • 2021-01-17 05:14

    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.

    0 讨论(0)
  • 2021-01-17 05:26

    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.

    0 讨论(0)
  • 2021-01-17 05:28

    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.

    0 讨论(0)
  • 2021-01-17 05:33

    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
    
    0 讨论(0)
提交回复
热议问题