问题
I need to show the cumulative power of all our energy projects by their online date.
So, if a project came online in 2016, it was also online in 2017 and 2018 and should be counted in those totals. I basically need a table that answers the questions
"What was our energy capacity as of 12/31/2016, 12/31/2017,etc"
I can do it by running a simple query over and over with different dates, but ideally I would run just one query and get the table I need.
I don't actually know how to code in SQL, so I just use the Access query designer, which might be making things more difficult.
Simple Query that gets what I want:
SELECT Sum(Projects.[System Size AC]) AS [SumOfSystem Size AC]
FROM Projects
WHERE (((Projects.[Online Date])<#1/1/2018#));
Query that gets an error:
SELECT DSum([Projects]![System Size AC],[Projects],Year([Online Date])<=[Yr]) AS [Run Sum], Year([Online Date]) AS Yr
FROM Projects
GROUP BY Year([Online Date]);
I can do it by running the simple query over and over with different dates, but ideally I would get one table with all the years in the online date column with like a cumulative total of all available project capacity available during that year
回答1:
You can do this using a correlated subquery:
SELECT Year(p.[Online Date]) as yr,
SUM(p.[System Size AC]) as this_year,
(SELECT SUM(p2.[System Size AC])
FROM Projects as p2
WHERE YEAR(p2.[Online Date]) <= YEAR(p.[Online Date])
) as running_sum
FROM Projects as p
GROUP BY Year([Online Date]);
来源:https://stackoverflow.com/questions/57042245/access-cumulative-total-by-date