google-sheetsgoogle-sheets-formulaarray-formulasgoogle-query-languagetop-n

3 latest values, but only for a specific user


I am trying to get the average of the 3 latest values, but only for a specific user.

The range of C are the dates, the range of G are the values I am trying to find the average of, and the range of A are the users.

=ArrayFormula(IFERROR(average(query(IF(len('Month Tracker'!$C:$C),{ROW('Month Tracker'!$C:$C),'Month Tracker'!$G:$G},),"Select Col2 where Col2>0 order by Col1 Desc limit 3"))))

This formula works for getting the average of the latest 3 values for all the users. However, I need for it to look through Month Tracker'!$A$2:$A and apply the formula only if the user in Month Tracker'!$A$2:$A matches the user in A2 in the current sheet... finding the average of the latest 3 values for that user only.


Solution

  • Your formula does not really return rows with latest dates. It just returns rows which are at the bottom. It probably just happens so that your latest dates are at the bottom, but formula never actually checks it as long as they are at the bottom.

    Another thing, ArrayFormula does not seem needed in this case.

    This is what you can use for your current problem:

    =IFERROR(AVERAGE(QUERY(IF('Month Tracker'!$C:$C,{'Month Tracker'!$C:$C,'Month Tracker'!$G:$G,'Month Tracker'!$A:$A},),"SELECT Col2 WHERE Col2>0 AND Col3="""&A2&""" ORDER BY Col1 DESC LIMIT 3")))
    

    If you really need, you can wrap it with ArrayFormula.