I want to Calculate average hours for week.
eg My Weekly hours are 44:43 (hh:mm) and my Working days are 5 then it should return 8:57
44:43/ 5 ==> 8:57
How i can achieve in SQL Server.
You can convert the time to seconds, then divide, and convert back to time format. Assuming that WeeklyHours
are in a time
format, something like this:
select dateadd(second, datediff(second, 0, WeeklyHours) / WorkingDays, cast(0 as time))
This expression should definitely work if WeeklyHours
is stored as a datetime
.
SELECT CONVERT(VARCHAR,CONVERT(INT,DATEPRT(HH,WH))/5)+':'+
+CONVERT(VARCHAR,(CONVERT(INT,DATEPRT(HH,WH))%5*60+CONVERT(INT,DATEPRT(mm,WH)))/5)
fROM TIME
Here's the query that I have constructed as per your requirements:
DECLARE @TotalHours VARCHAR(5) = '44:43'
SELECT CAST(CAST(AvgMinutes AS INT)/60 AS VARCHAR) + ':'
+ CAST(CAST(AvgMinutes AS INT)%60 AS VARCHAR)
FROM (
SELECT CEILING((CAST(LEFT(@TotalHours,CHARINDEX(':',@TotalHours) - 1) AS INT ) * 60
+ CAST(RIGHT(@TotalHours,LEN(@TotalHours) - CHARINDEX(':',@TotalHours)) AS INT ))/5.0) AvgMinutes
) AS TotalMinutes
Not getting the calculation. What I am trying to get is (44 + (43 / 60)) / 5. I did 43/60 to convert the mins to hours. As per this requirement, the query comes as
select (cast(SUBSTRING(Data, 1, charindex(':',Data,1) - 1) as int) +
(cast(SUBSTRING(Data, charindex(':',Data,1) + 1, len(Data)) as decimal(18,2)) / 60)) / 5
from tblWorkHours
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.