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
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


Did you like this post?
kick it on DotNetKicks.com
subscribe via rss subscribe via e-mail
print this post follow me on twitter


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

 
  Feedback:

comments

1 Response to "SQL Server 2008: Divide Time Column with Another Column"
  1. --CELKO-- said...
    July 8, 2011 at 8:54 AM

    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.

 

Copyright © 2009-2014 All Rights Reserved for SQLServerCurry.com by Suprotim Agarwal | Terms and Conditions