google-sheetsdynamicdropdowngoogle-query-language

Google sheet query to sum columns dynamically determined by a multi-choice selection from a dropdown


I have a table in a Google sheet that looks like this:

company 2024Q1 2024Q2 2024Q3 2024Q4
A $100 $50 $95 $12
B $200 $35 $54 $9
C $0 $40 $23 $12

I use data validation to create a dropdown (from a range) and allowing multiple selections, such that I can choose any combination of quarters to sum together.

For example, to sum Q1, Q2, and Q4 I use this query

=query(A2:E4, "select Col1, Col" & XMATCH("2024Q1", A1:E1) & " + Col" & XMATCH("2024Q2", A1:E1) & " + Col" & XMATCH("2024Q4", A1:E1))

But I want to build this query dynamically from the values selected in the dropdown. I tried to split and then join the selected values, then use concatenate to add the pre and post joined parts, like:

=query(A2:E4, CONCATENATE("select Col1, Col", CHAR(34), " & XMATCH(", CHAR(34), JOIN(CHAR(34) & ", A1:E1) & " & CHAR(34) & " + Col" & CHAR(34) & " & XMATCH(" & CHAR(34), SPLIT(A8, ", ")), CHAR(34), ", A1:E1)"))

It looks like CONCATENATE is return a literal string, rather than a SELECT command. I've tried many different ways e.g., moving the select outside the concatenate, to no avail.

Any ideas? I figure there must be a much simpler way to do this.


Solution

  • SUM Columns dynamically

    =LET(a, BYCOL(SPLIT(F1,", "),LAMBDA(x,FILTER(A2:E4,A1:E1=x))),
         b, A2:A4,
         c, HSTACK(b,a),
         d, BYROW(c,LAMBDA(x,sum(x))),
         HSTACK(b,d))
    

    Sample Input

    Company 2024Q1 2024Q2 2024Q3 2024Q4
    A $100 $50 $95 $150
    B $200 $35 $54 $235
    C $0 $40 $23 $40

    Sample Output

    2024Q1, 2024Q2 (Dropdown)
    A $150
    B $235
    C $40

    References:

    BYCOL

    LAMBDA

    FILTER