Link to home
Start Free TrialLog in
Avatar of RDLFC
RDLFC

asked on

SQL select trailing two day average

I have a table with dates in one column and total in the second one

Date            Total
01-Jan-15      5
02-Jan-15      4
03-Jan-15      3
04-Jan-15      12
05-Jan-15      14
06-Jan-15      7
07-Jan-15      9

I want to run a query that will return a trailing two day average.  it should return the following

01-Jan-15      
02-Jan-15        4.5
03-Jan-15        3.5
04-Jan-15        7.5
05-Jan-15      13
06-Jan-15      10.5
07-Jan-15        8
ASKER CERTIFIED SOLUTION
Avatar of ste5an
ste5an
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
;WITH   NumberedRows
AS
(
    SELECT  rta.*, row_number() OVER (ORDER BY rta.ID ASC) AS RowNumber
    FROM    test10k rta
)

SELECT  nr.ID, nr.Number,
    avg(trailing.Number) as MovingAverage
FROM    NumberedRows nr
    join NumberedRows as trailing on trailing.RowNumber between nr.RowNumber-3 and nr.RowNumber-1
where nr.Number > 3
group by nr.id, nr.Number

Ref. https://stackoverflow.com/questions/911326/sql-select-statement-for-calculating-a-running-average-column