0

I need to calculate average of date differences excluding weekends across rows in a column. The query gives me wrong results. But, when i calculate it myself, i get different results. the query is something like -

select zone, avg(datediff(dd,startdate,enddate)-datediff((ww,startdate,enddate)*2)) from table where startdate >'1/1/2013' group by zone

I don't get correct results. Please guide me.

user1416631
  • 195
  • 1
  • 4
  • 15

2 Answers2

0

try this code:

    select zone , avg(NumOfDays) from
          (select zone, (datediff(dd,startdate,enddate)-datediff((ww,startdate,enddate)*2)) as         NumOfDays from table where startdate >'1/1/2013')
    group by zone
Katy
  • 286
  • 2
  • 18
0

I don't know how your data looks like and what you challenge exactly is but I think your problem is "excluding weekend"? Maybe this helps you?

First create a function that counts every weekend day between your period for filtering it later:

CREATE FUNCTION fnc_GetWeekendDays(@dFrom DATETIME, @dTo   DATETIME)
RETURNS INT AS
BEGIN
   Declare @weekendDays int
   Set @weekendDays = 0

   While @dFrom <= @dTo 
   Begin
      If ((datepart(dw, @dFrom) = 1) OR (datepart(dw, @dFrom) = 7))    
                  Set @weekendDays = @weekendDays + 1
                  Set @dFrom = DateAdd(d, 1, @dFrom)

    End
   Return (@weekendDays)
END

After this, write your query:

Select
zone,
avg(cast((datediff(SECOND,StartTime,EndTime) - dbo.fnc_GetWeekendDays(StartTime, EndTime)*86400) as float))
from
    (
        Select zone,
        CASE 
            WHEN (datepart(dw, startdate) = 1) THEN DATEADD(Day, DATEDIFF(Day, 0, startdate), 1) 
            WHEN (datepart(dw, startdate) = 7) THEN DATEADD(Day, DATEDIFF(Day, 0, startdate), 2) 
            ELSE startdate END as StartTime, 
        CASE 
            WHEN (datepart(dw, enddate) = 1) THEN DATEADD(Day, DATEDIFF(Day, 0, enddate), -2) 
            WHEN (datepart(dw, enddate) = 7) THEN DATEADD(Day, DATEDIFF(Day, 0, enddate), -1) 
            ELSE enddateEND as EndTime
        from  table
    ) subquery
where StartTime < EndTime and startdate >'2013-01-01 00:00:00.000'
Group by zone

You will get your average time in seconds, if you want another format you have to calculate it...

Nelly
  • 522
  • 6
  • 15