Search code examples
arraysgoogle-sheetsstring-formattingarray-formulasgoogle-query-language

I want to apply, to a whole column, a formula that is already an arrayformula


I have a ledger with a bunch of expenses listed by date, category, and amount. Expenses ledger

Separately I have an analytics sheet for one category, "Gas". I want the analytics sheet to show total gas expenditures month by month without having to update anything other than the ledger. I can get a list of unique months with this formula:
=UNIQUE(ARRAYFORMULA(DATE(YEAR('Main Ledger'!A2:A), MONTH('Main Ledger'!A2:A), 1)))
This populates the months the way I want, and the list will automatically grow with the ledger. I put these in column A.

For each month, I want to compare every entry in the ledger against the date in column A and the category "Gas". I can do that for a single month with the following formula in column B:

=ArrayFormula(SUMIFS('Main Ledger'!D$2:D,MONTH('Main Ledger'!A$2:A),MONTH(A2),YEAR('Main Ledger'!A$2:A),YEAR(A2),'Main Ledger'!F$2:F,"Gas"))

Gasoline analytics

Because I have to use arrayformula to make the date comparison on the ledger, I'm having trouble figuring out how to then use arrayformula to automatically apply this monster formula to all of column B. As column A grows (automatically because of UNIQUE, I want column B to grow too.

I do not want to prepopulate column B and have a bunch of zeroes lying around, mainly because I will be using columns A and B to populate a chart.


Solution

  • try in one go:

    =QUERY({Sheet1!A2:D}, 
     "select month(Col1),sum(Col4) 
      where Col4 is not null
      group by month(Col1) 
      label month(Col1)'month'")
    

    enter image description here


    update:

    =INDEX(ARRAY_CONSTRAIN(QUERY({TEXT(Sheet1!A2:A, "mmmm"), Sheet1!A2:D}, 
     "select Col1,sum(Col5),month(Col2) 
      where Col5 is not null
      group by month(Col2),Col1 
      label Col1'month'"), 9^9, 2))
    

    enter image description here