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
UNION ALL
SELECT 'Fixtures', '05:26:50.0000000', 3
UNION ALL
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))/
SUM(NoOfWorkers)
as [Average Time Per Person (in seconds)]
FROM @Timesheet
GROUP BY NatureOfWork


OUTPUT

SQL Server Time Divide


About The Author

Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and a new one recently at The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigous Microsoft MVP award for nine times in a row now. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that represents premium web sites and digital publications comprising of Professional web, windows, mobile and cloud developers, technical managers, and architects.

Get in touch with him on Twitter @suprotimagarwal, LinkedIn or befriend him on Facebook

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.