views:

49

answers:

2

I need help writing select statement that will do an average of the most recent 52 rows of data.

If there is less then 52 rows it will only do the avg of how many rows there are.

I know the avg function in SQL will skip the null...but i got this far.

SELECT AVG(E.Interest)
from InterestRates E
Where Interest in (select COUNT(Interest) <=52 from InterestRates)

i wanted for each row of data to go back and calculate the avg 52 rows thanks

+4  A: 

Try this:

SELECT AVG(Interest) AS AvgInterest
FROM (
    SELECT TOP 52 E.Interest
    FROM InterestRates E
    ORDER BY DateEntered DESC
) Top52Interests

EDIT

Based on comments you can order by the identity instead:

SELECT AVG(Interest) AS AvgInterest
FROM (
    SELECT TOP 52 E.Interest
    FROM InterestRates E
    ORDER BY YourIdentityField DESC
) Top52Interests

The nice thing is this query will work in SQL 2000 as well.

LittleBobbyTables
A: 

SELECT AVG(E.Interest) FROM
InterestRates E WHERE ROWNUMBER() <= 52 ORDER BY whatever DESC;

vulkanino