I have the following datasource in a GoogleSheet:
DATE | PROJECTED | BALANCE |
---|---|---|
01/01/2025 | FALSE | $3,824.54 |
01/16/2025 | FALSE | $2,366.39 |
01/21/2025 | FALSE | $3,783.64 |
01/22/2025 | TRUE | $3,750.72 |
01/28/2025 | TRUE | $3,150.72 |
02/03/2025 | TRUE | $135.72 |
02/04/2025 | TRUE | $2,974.45 |
02/12/2025 | TRUE | $2,863.16 |
02/18/2025 | TRUE | $4,153.66 |
02/25/2025 | TRUE | $3,553.66 |
03/03/2025 | TRUE | $538.66 |
03/04/2025 | TRUE | $3,377.39 |
Using a QUERY function, I want to get the BALANCE when PROJECTED is TRUE for the MAX DATE per MONTH. The expected outcome should be the following:
Month | Max Date | Balance |
---|---|---|
1 | 01/28/2025 | $3,150.72 |
2 | 02/25/2025 | $3,553.66 |
3 | 03/04/2025 | $3,377.39 |
My initial approach was the following formula:
=QUERY('2025'!A2:C,
"SELECT MONTH(Col1)+1, MAX(Col1), SUM(Col3)
WHERE Col2=TRUE
GROUP BY MONTH(Col1)
LABEL MONTH(Col1)+1 'Month', MAX(Col1) 'Max Date', Sum(Col3) 'Balance'")
Then I realized I needed another WHERE condition over Col1 to pull Col3 data based on that. I defined the following query:
=QUERY('2025'!A2:C,
"SELECT MAX(Col1)
WHERE Col2=TRUE
GROUP BY MONTH(Col1)
LABEL MAX(Col1) '' ")
The outcome was:
01/28/2025 |
02/25/2025 |
03/04/2025 |
In order to be inserted as value in the original query, I need to apply a format condition to literal, as follow:
=TEXT(QUERY('2025'!A2:C,
"SELECT MAX(Col1)
WHERE Col2=TRUE
GROUP BY MONTH(Col1)
LABEL MAX(Col1) '' "),
"yyyy-MM-dd")
But the outcome was the following:
2025-01-28 |
What happened with the other two lines for Feb and March?
At the end, the final query, should look like this one:
=QUERY('2025'!A2:C,
"SELECT MONTH(Col1)+1, MAX(Col1), SUM(Col3)
WHERE Col2=TRUE
AND Col1 MATCHES DATE '"&TEXT(QUERY('2025'!A2:C,"SELECT MAX(Col1) WHERE Col2=TRUE GROUP BY MONTH(Col1) LABEL MAX(Col1) '' "),"yyyy-mm-dd")&"'
GROUP BY MONTH(Col1)
LABEL MONTH(Col1)+1 'Month', MAX(Col1) 'Max Date', Sum(Col3) 'Balance'")
But I'm getting the following:
Month | Max Date | Balance |
---|---|---|
1 | 01/28/2025 | $3,750.72 |
What happened with the other two lines for Feb and March?
I don't think there's a straightforward way to solve this problem using exclusively the QUERY
function.
Here's what you can try instead:
=ARRAYFORMULA(LET(
data, A2:C,
max_dates, QUERY(data,
"SELECT MAX(Col1)
WHERE Col2 = TRUE
GROUP BY MONTH(Col1)
LABEL MAX(Col1) ''"
),
VLOOKUP(max_dates, {data, MONTH(data)}, {4, 1, 3}, )
))
This formula first finds the max dates using a simple query, then it runs a vlookup on them to get the corresponding balances.