sqlgoogle-apps-scriptgoogle-sheets

google spreadsheet query function column id other than letter of column


alright... not sure if these could be done.

i'm in google spreadsheets with cell A1 = time.. the range is A1:C4.

i have a simple table as follows:

time   sit   stand 
1      bob   mike
2      fred  pat
3      chris mike

This my query:

=query($A$1:$C$4,"select A,B,C where C='mike'",0) 

... pretty straight forward. however, I want the column reference to be dynamic. So i need to be able to query using the header. how do i do it? I've already tried the following:

=query($A$1:$C$4,"select 'sit ', 'stand' where 'stand' = 'mike' ",0)

=query($A$1:$C$4,"select sit, stand where stand = 'mike' ",0)

and per this page's suggestion: Google spreadsheet Query Error - column doesn't exist

I've also tried the following:

=query($A$1:$C$4,"select Col2, Col3  where Col3 = 'mike' ",0)

=query($A$1:$C$4,"select Col2, Col3  where (Col3) = 'mike' ",0)

=query($A$1:$C$4,"select (Col2), (Col3)  where (Col3) = 'mike' ",0)

=query($A$1:$C$4,"select 'Col2', 'Col3'  where 'Col3' = 'mike' ",0)

None of them work... does anybody know how to do it or know if it is possible?

https://developers.google.com/chart/interactive/docs/querylanguage

the examples here seems like you can do it, but is that for app script only? and not in the spreadsheet function?


Solution

  • Unfortunately there is no native way of referencing columns by their headers in the QUERY spreadsheet function select clause.

    You can use the Colx notation if the first argument of the QUERY is anything other than an explicitly referenced range. One way to achieve this is wrap the range in parentheses, and invoking ArrayFormula:

    =ArrayFormula(QUERY(($A$1:$C$4),"select Col2, Col3 where Col3 = 'mike'",0))

    And it is rather ugly, but you can use the MATCH function to bolt in header references:

    =ArrayFormula(QUERY(($A$1:$C$4),"select Col"&MATCH("sit";$A$1:$C$1;0)&", Col"&MATCH("stand";$A$1:$C$1;0)&" where Col"&MATCH("stand";$A$1:$C$1;0)&" = 'mike'",1))