|
|
Question : Datediff - average
|
|
I've got the following fields in my table: CreatedOn & FirstSendingToOperator (both small datetime)
What do I want to achieve: For every record where the CreatedOn is in a specific month (for example march 2005), I want to get the following result:
Workday - Average difference days (between dates) - Number of records for that day
for example
1 - 3 - 6 2 - 0 - 0 (instead of null) 3 - 1 - 1 4 - 5 - 3
so on the first day of the month, i have a average of 3 days between the two dates and there were 6 records logged for that day.
Note: the both dates must be filled in !!! (so I'll probably have to add a check to the query ?)
|
Answer : Datediff - average
|
|
Oops, also need to change nulls with 0s
select A.day_number, ISNULL(item_count,0) as item_count, ISNULL(average_work,0) as average_work from ( select 1 as day_number union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9 union all select 10 union all select 11 union all select 12 union all select 13 union all select 14 union all select 15 union all select 16 union all select 17 union all select 18 union all select 19 union all select 20 union all select 21 union all select 22 union all select 23 union all select 24 union all select 25 union all select 26 union all select 27 union all select 28 union all select 29 union all select 30 union all select 31) A LEFT OUTER JOIN ( SELECT DATEPART([day], CreatedOn) AS day_number, COUNT(*) AS item_count, AVG(DATEDIFF([day], CreatedOn, FirstSendingToOperator)) AS average_work FROM dbo.tbl5414488001308 WHERE (CreatedOn IS NOT NULL) AND (FirstSendingToOperator IS NOT NULL) AND (MONTH(CreatedOn) = 3) AND (YEAR(CreatedOn) = 2005) GROUP BY DATEPART([day], CreatedOn) ) B on A.day_number = B.day_number WHERE A.day_number <= day(dateadd(day,-1,dateadd(month,1,cast(2005 as varchar) + '.' + cast(3 as varchar) + '.01'))) order by A.day_number
|
|
|
|
|