Search This Blog

Showing posts with label sum hours. Show all posts
Showing posts with label sum hours. Show all posts

Sunday, September 26, 2010

SUM of Hours and Minutes SQL 2005

Hi,

I came across a post where one of our fellow SQL coleague asked a question i.e. In SQL Server 2005 how to do SUM of Hours and Minutes. So here comes rest of story:

Problem Description
***********************
I want to get SUM of Hours and Minutes in SQL Server 2005 in To SELECT Query Like : SELECT SUM(OTHours) FROM EmpInOutRecords.

Example: I Have OverTime Hours Like: 01:25, 02:30, 05:56, 00:50

Now I Want To SUM of This Total Hours and Minutes Like Answer is : 10:41

Resolution Code
****************

DECLARE @Sample TABLE
( data CHAR(5)
)


INSERT @Sample SELECT '01:25' UNION ALL
SELECT '02:30' UNION ALL
SELECT '05:56' UNION ALL
SELECT '00:50'
SELECT
STUFF(CONVERT(CHAR(8), DATEADD(SECOND, theHours + theMinutes, '19000101'), 8), 1, 2, CAST((theHours + theMinutes) / 3600 AS VARCHAR(12)))
FROM (
SELECT ABS(SUM(CASE CHARINDEX(':', data) WHEN 0 THEN 0 ELSE 3600 * LEFT(data, CHARINDEX(':', data) - 1) END)) AS theHours,
ABS(SUM(CASE CHARINDEX(':', data) WHEN 0 THEN 0 ELSE 60 * SUBSTRING(data, CHARINDEX(':', data) + 1, 2) END)) AS theMinutes
FROM @Sample
) AS d