Create Absence Run Rates

Hi, I'm looking to create a table in SQL Server looking at the archived data and supplying what the relevant 4 week run rate was at any given time. For example, today is Friday the 7th of April so I'd like the table to look at the last 4 Fridays and average what the actual absence hours were:

|10/03/2023| 223|
|17/03/2023| 217|
|24/03/2023| 251|
|31/03/2023| 248|
|07/04/2023 (Avg RR)| 235|

The archive runs once a day for 7 days in the past and 90 days forward, so there will be multiple entries for the 7th of April. To avoid any duplication I'd only need it to look at the job one day out - the absence for the 31st of March from the job ran on the 1st of April.

I have the solution in excel but I'm struggling to translate that on SQL. Any help would be appreciated.

Thanks,
Gary

Excel Solution

Hi

Hope this helps

Just an idea

That >= needs to be adjusted based on your data

Select 
  Date column
    , RR
 From 
       Table
Where 
       Date column >= datediff(dd,-28, date column)
       
 Union all
 
 Select 
  Date column
    , Avg( RR )
 From 
       Table
Where 
       Date column >= datediff(dd,-28, date column)

Hi Harish,

I've tried a few variations of that but it isn't pulling the right hours for some reason. Here's how I have the query at the moment:

  SELECT     
   [Date]
  ,[Skill]
  ,[Weekday]
  ,avg(Absence) as Absence

  FROM [dbo].[Archive]
  where datediff(day,[Job Date],[Date]) = -1 
  and Date >= cast (getdate()-28 as date)
  group by skill, Weekday, Date 

For the 7th of April using the same data source as above, the Absence hours returned are 212 rather than 235. Not sure what the cause of the difference is.

hi

do you have any idea how to debug

take individual records ... and examine using queries

please try this

some times this is the issue
when you put aggregate functions directly

; with cte as 
(
SELECT     
   [Date]
   , [Skill]
   , [Weekday]
   , Absence
FROM 
  [dbo].[Archive]
WHERE 
    datediff(day,[Job Date],[Date]) = -1 
        AND  
	Date >= cast (getdate()-28 as date)
) 
select  [Date], [Skill] , [Weekday], AVG(Absence) as Absence
from cte 
group by skill, Weekday, Date