Search code examples
arraysgoogle-sheetsgoogle-sheets-formulasequencegoogle-query-language

How to Add Row Index of each data row using Query() function in Google Sheets?


Is there a way to get the row index using Query function like using row() function but inside a query?

enter image description here

Here is my query SQL. The query source are from 2 different sheets. So the row index should restart to 1 when the next source is being selected into the query.

={
                query(IMPORTRANGE('Static Data'!$B$2,'Static Data'!$B$3),
                        "select Col" &  ArrayFormula(textjoin(", Col",true,column('Static Data'!$A$22:$AC$22))) & ", 'BAU'
                        where 
                        Col"& 'Static Data'!$B$22 &" is not null
                        label 'BAU' 'SOURCE'", 
                1);
                
                query(IMPORTRANGE('Static Data'!$B$2,'Static Data'!$B$5),
                        "select Col" &  ArrayFormula(textjoin(", Col",true,column('Static Data'!$A$22:$AC$22))) & ", 'ICS'
                        where 
                        Col"& 'Static Data'!$B$22 &" is not null
                        label 'ICS' ''", 
                0)`}

EDIT (24/Aug/2021):

Final code that works looks like this after the suggestions from the comments below. I moved the rowId to the end of the table coz that's where I want it to be positioned.

=INDEX({QUERY({IMPORTRANGE('Static Data'!$B$2, 'Static Data'!$B$3),SEQUENCE(ROWS(
 IMPORTRANGE('Static Data'!$B$2, 'Static Data'!$B$3)))},
 "select Col1,Col"&TEXTJOIN(",Col", 1, 1+COLUMN('Static Data'!$A$22:$AC$22))&",'BAU'
  where Col"&1+'Static Data'!$B$22&" is not null
  label 'BAU''SOURCE'", 1);
 QUERY({IMPORTRANGE('Static Data'!$B$2, 'Static Data'!$B$5),SEQUENCE(ROWS(
 IMPORTRANGE('Static Data'!$B$2, 'Static Data'!$B$5)))+1},
 "select Col1,Col"&TEXTJOIN(",Col", 1, 1+COLUMN('Static Data'!$A$22:$AC$22))&",'ICS'
  where Col"&1+'Static Data'!$B$22&" is not null
  label 'ICS'''", )})

Solution

  • try more compact:

    =INDEX({QUERY({SEQUENCE(ROWS(
     IMPORTRANGE('Static Data'!B2, 'Static Data'!B3))), 
     IMPORTRANGE('Static Data'!B2, 'Static Data'!B3)},
     "select Col1,Col"&TEXTJOIN(",Col", 1, 1+COLUMN('Static Data'!A22:AC22))&",'BAU'
      where Col"&1+'Static Data'!B22&" is not null
      label 'BAU''SOURCE'", 1);
     QUERY({SEQUENCE(ROWS(
     IMPORTRANGE('Static Data'!B2, 'Static Data'!B5))),
     IMPORTRANGE('Static Data'!B2, 'Static Data'!B5)},
     "select Col1,Col"&TEXTJOIN(",Col", 1, 1+COLUMN('Static Data'!A22:AC22))&",'ICS'
      where Col"&1+'Static Data'!B22&" is not null
      label 'ICS'''", )})
    

    enter image description here