简体   繁体   中英

sum of time datatype in sql

i have a table named tblAttendanceDailySummary and there is a field is in time datatype named timeAttendanceHour(like 09:44:25). I want to sum of this field due to end of the month.I mean one employee's one month working time need to calculate.How can i sum time datatype.

The time data type has a range of 00:00:00.0000000 through 23:59:59.9999999 so you can't cast to time. You have to calculate the hour, minute and second instead.

Something like this could work for you

select H.Val, M.Val, S.Val
from (
       --Your query goes here
       select dateadd(second, sum(datediff(second, 0, timeAttendanceHour)), 0) as sumtime
       from YourTable
     ) as T
  cross apply (select datedifF(hour, 0, T.sumTime)) as H(Val)
  cross apply (select datediff(minute, 0, dateadd(hour, -H.Val, T.sumTime))) as M(Val)
  cross apply (select datediff(second, 0, dateadd(hour, -H.Val, dateadd(minute, -M.Val, T.sumTime)))) as S(Val)

If you want the result as HH:MM:SS you can use this:

select cast(H.Val as varchar(10))+':'+right(M.Val+100, 2)+':'+right(S.Val+100, 2)

How about converting the components to a standard integer and summing them:

select sum(second(timeAttendanceHour))/60 +
sum(minute(timeAttendanceHour)) +
sum(hour(timeAttendance))*60 as MonthlyMinutes,
intMonthID
from tblAttendanceDailySummary
where intYear = 2012
group by intEmployeeID, intMonthID

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM