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
RDLFCAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

ste5anSenior DeveloperCommented:
E.g.

DECLARE @Sample TABLE ( dt DATE, Total INT );

INSERT  INTO @Sample
VALUES  ( '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 );

SELECT  O.* ,
        ( SELECT    AVG(1.0 * I.Total)
          FROM      @Sample I
          WHERE     I.dt BETWEEN DATEADD(DAY, -1, O.dt) AND O.dt
        ) AS SlidingAverage
FROM    @Sample O
ORDER BY O.dt ASC;

Open in new window


In SQL Server 2012+ you would use the enhanced OVER clause instead of a correlated sub-query.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Aland CoonsSystems EngineerCommented:
;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
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server 2008

From novice to tech pro — start learning today.