google-sheetsgoogle-sheets-formula

Can a label in a Google Sheets Query be dynamic; can it reference a variable?


In QUERY, labels can be created with a text value. Example: label Col2 'Total'
This will display "Total" instead of the existing label for Column 2.

But what if the query uses a dropdown as a means of filtering the results. In this case, the value of a "new" label might not be predictable and an end user might not be able/permitted to edit the query. So, can a label value be dynamic?

Say Cell A1 contains the word "Total".
Instead of writing label Col2 'Total', is it possible to substitute the value of cell A1 as the new label value?

For instance, if Cell A1 = "Grand Total", the label would change from "Total" to "Grand Total".


Solution

  • Concatenating a range in a Query as a label

    Formula:

    =QUERY(A2:B7, "SELECT A, SUM(B) GROUP BY A LABEL SUM(B) '" & C1 & "'")
    

    Changing the value in C1 instantly updates the column label in the result.

    Instead of hardcoding the formula use the & operator to dynamically refer to the value in C1 or your desired cell.

    Sample Output:

    Output

    Note: I just created sample data to demonstrate how to reference another cell.