I am making an attendance system in which I will add monthly records of employee time in and time out. At the end of the month average time in and time out will be created.
Please tell me how to apply avg() to datatype of time(7)?
declare @tblPK table
(
timeinat varchar(13) not null,
timeoutat varchar(13) not null
) ;
insert into @tblPK
select cast((onattendance) as varchar(13))ONTime,
cast((offattendance) as varchar(13))OFFTime
from t_attendancedetails ;
select * from @tblPK ;
This is only giving output of all entries.
Calculating average with a precision of millisecond using
time(7)columns.The query uses
datediffto get the difference in milliseconds betweenonattendanceandoffattendance. Then it uses the aggregate functionavgto calculate the average difference in milliseconds and finally it usesdateaddto add the average number of milliseconds to thetime(7)value00:00.Ref:
DATEDIFF (Transact-SQL)
DATEADD (Transact-SQL)
AVG (Transact-SQL)
CAST and CONVERT (Transact-SQL)
Update:
When calculating the average with a precision of
time(7)you need to split the time in two parts becausedatediffanddateadddoes not deal withbigint.The time difference values is converted to nanoseconds before average is calculated and the conversion back to
time(7)is done in two steps, first the seconds and then the nanoseconds.