Home All Groups Group Topic Archive Search About
Author
8 Jul 2005 7:10 PM
Phill
How do I calculate a 3 year moving average from within a stored procedure?  I
can do an average for each year, but not a moving average.  Thanks

Author
8 Jul 2005 7:15 PM
Aaron Bertrand [SQL Server MVP]
An average of what?
Please post DDL, sample data and desired results.
See http://www.aspfaq.com/5006 for info.




Show quote
"Phill" <Ph***@discussions.microsoft.com> wrote in message
news:C7A80551-48DB-4479-A7D6-55871B76565A@microsoft.com...
> How do I calculate a 3 year moving average from within a stored procedure?
> I
> can do an average for each year, but not a moving average.  Thanks
Author
8 Jul 2005 7:41 PM
Phill
The query selects the year, sum of outage minutes, number of customers, and
number of customers per feeder.  Sample data:

Year      Minutes      Customers  Customers/Feeder
1998    220    62900    1000
1999    1258    63735    1000
2000    320    64868    1000
2001    875    65107    1000
2002    621    66458    1000
2003    63    66458    1000
2004    170    67450    1000
2005    858    67435    920

The calculation is (Minutes * Customers per Feeder) / total customers
So, for 2005 it would be (858 * 920)/67435 = 11.71

What I need is to calculate the moving average for 2005, 2004, 2003, etc.
Does this help?


Show quote
"Aaron Bertrand [SQL Server MVP]" wrote:

> An average of what?
> Please post DDL, sample data and desired results.
> See http://www.aspfaq.com/5006 for info.
>
>
>
>
> "Phill" <Ph***@discussions.microsoft.com> wrote in message
> news:C7A80551-48DB-4479-A7D6-55871B76565A@microsoft.com...
> > How do I calculate a 3 year moving average from within a stored procedure?
> > I
> > can do an average for each year, but not a moving average.  Thanks
>
>
>
Author
9 Jul 2005 2:39 AM
--CELKO--
There are OLAP functions coming in SQL:2005, but a quick way is to
build a table with year ranges in it:

CREATE TABLE YearRanges
(start_year INTEGER NOT NULL,
end_year INTEGER NOT NULL,
CHECK (start_year  - end_year = 2),  -- adjust as needed
PRIMARY KEY (start_year,  end_year));

Now the query is easy:

SELECT F.year_nbr, (SUM(minutes_down) * SUM( cust_feeder) ) / SUM
(cust_cnt)
  FROM Foobar AS F, YearRanges AS Y
WHERE F.year_nbr BETWEEN Y.start_year  AND Y.end_year;
Author
8 Jul 2005 7:36 PM
Anith Sen
Try providing more info as Aaron requested. For something based on guess
work, try a correlated subquery like:

SELECT ...., t1.dt,
       ( SELECT AVG( t2.dt )
           FROM tbl t2
          WHERE t2.dt BETWEEN DATEADD( year, -3, t1.dt ) AND t1.dt )
  FROM tbl t1 ;

--
Anith

AddThis Social Bookmark Button