| Author |
Topic |
|
ashley.sql
Constraint Violating Yak Guru
299 Posts |
Posted - 2006-09-28 : 17:18:44
|
| THIS IS THE DATAcreate table #durations as (Contractor char(3), WORKERID int,Startdate datetime, Enddate datetime, SITE char(10))insert #durationsvaluesABC, 1, 1/1/2005, 1/31/2005, NYC1 union allABC, 1, 2/1/2005, 4/1/2005, NYC2 union allXYZ, 2, 2/1/2006, 3/31/2006, NYC1 union allXYZ, 2, 4/1/2006, 5/9/2007 , NYC union allABC, 3, 4/22/2005, null, nyc union allABC, 4, 1/1/2005, 1/31/2005, NYC1 union allABC, 4, 2/1/2005, 6/1/2005, NYC2 I need to find average no. of days a worker worked for each contractorHe may work on one site or may work on multiple sites as after working on one site he maybe transferred to anotherIf enddate > getdate() then (datediff(d, getdate(), min(startdate))of that worker. He may have many start dates and many end dates. So we take the subtract his minimum start date from todays date.If he has a end date which is less then today then we do thisdatediff(max(enddate(), min(enddate()) of that workerHis last end date is subtract from his first start dateSay this is sample dateContractor, WORKERID, Startdate, Enddate, SITEABC, 1, 1/1/2005, 1/31/2005, NYC1ABC, 1, 2/1/2005, 4/1/2005, NYC2XYZ, 2, 2/1/2006, 3/31/2006, NYC1XYZ, 2, 4/1/2006, 5/9/2007 , NYCABC, 3, 4/22/2005, null, nycABC, 4, 1/1/2005, 1/31/2005, NYC1ABC, 4, 2/1/2005, 6/1/2005, NYC2So for Worker 1we will do his max(enddate) 4/1/2005 - min(startdate) 1/1/2005and we will take average of all workers like this. Similar is worker 4.For worker 2 it since his end date is greate than today we will take todays date getdate()- min(startdate) 2/1/2006.for worker 3 the date is null so we calculate his duration asgetdate() - start dateso we group by each contractorsay for ABC, 1 3 and 4 worked 100 days eachso average would be 100 (300/3)Ashley Rhodes |
|
|
snSQL
Master Smack Fu Yak Hacker
1837 Posts |
Posted - 2006-09-28 : 17:57:06
|
Here is a query that should give you what you want along with a working version of your sample data.create table #durations (Contractor char(3), WORKERID int,Startdate datetime, Enddate datetime, SITE char(10))insert #durationsselect 'ABC', 1, '1/1/2005', '1/31/2005', 'NYC1' union allselect 'ABC', 1, '2/1/2005', '4/1/2005', 'NYC2' union allselect 'XYZ', 2, '2/1/2006', '3/31/2006', 'NYC1' union allselect 'XYZ', 2, '4/1/2006', '5/9/2007' , 'NYC' union allselect 'ABC', 3, '4/22/2005', null, 'nyc' union allselect 'ABC', 4, '1/1/2005', '1/31/2005', 'NYC1' union allselect 'ABC', 4, '2/1/2005', '6/1/2005', 'NYC2' SELECT contractor, avg(datediff(day, WorkerStartDate, WorkerEndDate)) AveragePerWorkerFROM(SELECT contractor, workerid, min(startdate) WorkerStartDate, case when max(isnull(enddate, getdate())) > getdate() then getdate() else max(isnull(enddate, getdate())) end WorkerEndDateFROM #durationsGROUP BY contractor, workerid) WorkerDatesGROUP BY contractor |
 |
|
|
|
|
|