I\'ve looked for a while and I cannot find the answer to this question (maybe I\'m not searching the correct terms or something). Basically, I have a database that has any n
Here is an idea using correlated subqueries:
with bydays as (<your query here>)
select bd.*,
(select sum(NumMeasured) from (select top 100 * from bydays bd2 where bd2.date <= bd.date order by date desc) t
) as Measured100,
(select sum(NumPassingd) from (select top 100 * from bydays bd2 where bd2.date <= bd.date order by date desc) t
) as Measured100
from bydays
To get your last 100 dates,
SELECT TOP(100) DISTINCT date FROM yield ORDER BY date desc
You can simplify your first query with something as simple as
SELECT date, SUM(passing) as numpassing, SUM(Measured) as nummeasured
FROM yield
GROUP BY date
If you need the sum from now until 100 days ago
SELECT SUM(passing) as npassing, SUM(measured) as nmeasured
FROM yield
WHERE date >= DATEADD(d,100,CURRENT)
And if you need the sum from the last 100 dates
SELECT SUM(passing) as npassing, SUM(measured) as nmeasured
FROM yield
WHERE date IN (SELECT TOP 100 date FROM yield WHERE date <= '04/05/2013' ORDER BY date desc)