For a conditional running average, assuming all entries in A2:A are grouped:
=ArrayFormula(IFERROR((SUMIF(ROW(A2:A),"<="&ROW(A2:A),B2:B)-HLOOKUP(0,SUMIF(ROW(A2:A),"<"&ROW(A2:A),B2:B),MATCH(A2:A,A2:A,0),0))/(ROW(A2:A)-MATCH(A2:A,A2:A,0)-ROW(A2)+2)))
Before the update to the newest version of Sheets a number of months ago, it would have generally been advised to use MMULT for these sort of "conditional running total" problems:
=ArrayFormula(IF(LEN(A2:A),MMULT((ROW(A2:A)>=TRANSPOSE(ROW(A2:A)))*(A2:A=TRANSPOSE(A2:A)),--B2:B)/MMULT((ROW(A2:A)>=TRANSPOSE(ROW(A2:A)))*(A2:A=TRANSPOSE(A2:A)),SIGN(ROW(A2:A))),))
This solution also has the added benefit that the A2:A column needn't be grouped, nor sorted. However, in the newest version, the MMULT solution will break when the referenced range reaches 3163 rows. It appears to be because the 2D array formed by MMULT will tip over 10 million elements (square root of 10 million = 3162.278...).
The first solution shouldn't suffer this limitation, however it will probably still get very slow when referencing a few thousand rows.
Grouping
In general, aggregation functions such as SUM or COUNT are used in the presence of GROUP BY: one specifies how to group the rows so that summation or counting is executed within each group. You don't have any GROUP BY. It would make sense to group by E, so that you count each client id once.
Date format
When dates are used in a query, they have to appear like date 'yyyy-MM-dd'
, for example
where A >= date '2017-05-01' and A <= date '2017-05-21'
Creating such a string from dynamic dates (e.g., 60 days ago, =TODAY()-60
involves conversion to text using text
and an annoying amount of concatenation:
"... where A >= date '" & text(today()-90, "yyyy-MM-dd") & "' and ..."
If you go this route, it is advisable to form the query string in its own cell so you can see what it is. query
can take the query string by cell reference.
Alternative: filter
It's much easier to use filter
for the task you described. Here is the count of unique values in E2:E where A entry is between 30 and 90 days ago:
=countunique(iferror(filter(E2:E, A2:A >= today()-90, A2:A <= today()-30)))
The wrapper iferror
is included to suppress "#N/A" that filter
returns when there are no matches. (As pointed out by ocWavean).
Best Answer
The formula I would use (assuming this started in column A) would be this:
This will find the change in kWh since the last reading, divide it by the number of days in the reading (to get the daily average) then multiply it by the number of days in that month.
Since you have already calculated the daily average (in column 4) you could just do
and you would get the same results. If you were trying to find a general month average (not tied to specific days in each month) you could just take column 4 * 30 (
=D2*30
).