Search code examples
google-sheetsgoogle-sheets-formula

Averaging over a table based on criteria not being met


I have a table that can't have headers (or I think I could use dsum for this, I have included headers in the example table for ease of explanation), I want to work out the average "price per" when bought or sold, but only if the row doesn't match a list of names.

So if I wanted to do this for all entries (rows) where items were Bought, but not if Origin was "SWAP" or "G COMM", I would look at the first row, see A it doesn't match "SWAP" or "G COMM", add C to a COUNT variable, and add B*C to a TOTAL variable. I would do this for all rows and at the end do TOTAL/COUNT to get the average "Price Per" based on how many were bought not matching my criterium.

So for that example, row 1 & 3 are bought rows with matching Origin criteria, ((185)+(173))/(5+3) = Average Price Per of 17.625

(A) Origin (B) Price Per (C) Bought (D) Sold
CITIZEN 18 5
" 20 14
" 17 3
" 20 3
COMM 24 5
CITIZEN 19 2
SWAP 14 16
G COMM 0 4

Solution

    • FILTER the data as needed
    • get both the filtered columns using INDEX and calculate as needed
    =LET(data,
      FILTER(B1:D8,
        A1:A8<>"SWAP",
        A1:A8<>"G COMM", 
        C1:C8<>""),
      priceper,INDEX(data,0,1), 
      qty,INDEX(data,0,2), 
      SUMPRODUCT(priceper*qty)/SUM(qty)
    )