July 05, 2011

SQL Server 2008: Divide Time Column with Another Column

Here’s a simple example that divides a SQL Server 2008 Time column with another to calculate the time taken per employee to finish the task.

Let’s see a sample table first

SQL Server Time Column

DECLARE @Timesheet table (
NatureOfWork varchar(15),
TimeSpent time,    
NoOfWorkers int )

INSERT INTO @Timesheet
SELECT 'Plumbing', '02:56:00.0000000', 5
SELECT 'Fixtures', '05:26:50.0000000', 3
SELECT 'Sweeping', '0:39:40.0000000',  2

In order to calculate the average time taken per worker to complete the task, we will need to divide the ‘TimeSpent’ column with the ‘No of Workers’ column. We will use the DATEDIFF function to return the time in seconds and then divide it by no. of workers to find the time taken by each worker to complete the task.
SELECT NatureOfWork,
SUM(DATEDIFF(SECOND, '00:00:00',TimeSpent))/
as [Average Time Per Person (in seconds)]
FROM @Timesheet
GROUP BY NatureOfWork


SQL Server Time Divide

About The Author

Suprotim Agarwal, ASP.NET Architecture MVP works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

1 comment:

--CELKO-- said...

Nice trick! The only thing I can see as a problem is when soemone works over 24 hours so that the time data type wraps around. That is not much of a probelm in the real world, and it shoudl be easy enough to catch and handle somehow.