Rolling count with array formula in Google Sheets

强颜欢笑 提交于 2021-01-29 06:12:56

问题


I have the dataset below. Col1 is given data and Col2 is the rolling count of the previous 5 rows of Col1 (inclusive).

Date      Col1  Col2
01/04/20  2     1
02/04/20  1     2 
03/04/20  4     3
04/04/20        3
05/04/20        3
06/04/20  5     3
07/04/20  2     3
08/04/20        2
09/04/20        2
10/04/20  1     3
11/04/20        2
12/04/20        1
13/04/20        1
14/04/20        1
15/04/20  1     1

Is there a way to use arrayformula to do this rather than inputting a count formula into every cell in Col2 going down?


回答1:


You can use Countifs with a condition on the rows:

=ArrayFormula(filter(countifs(B2:B,">0",row(B2:B),"<="&row(B2:B),row(B2:B),">"&row(B2:B)-5),A2:A<>""))

assuming the numbers are positive

To include any number, you can use:

=ArrayFormula(filter(countifs(isnumber(B2:B),true,row(B2:B),"<="&row(B2:B),row(B2:B),">"&row(B2:B)-5),A2:A<>""))

If you wanted to show rows corresponding to future dates as blanks, you could add an If statement:

=ArrayFormula(filter(if(A2:A>today(),"",countifs(isnumber(B2:B),true,row(B2:B),"<="&row(B2:B),row(B2:B),">"&row(B2:B)-5)),A2:A<>""))


来源:https://stackoverflow.com/questions/61442363/rolling-count-with-array-formula-in-google-sheets

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!