google-sheetsgoogle-sheets-formula

Stacking output of Google Sheets Queries together - Top 3 Dishes per Restaurant


I want to have a lambda run a query over items in a list, but I get an error "Result should be a single row." I want to have the outputs stack with each other, so that the sources can be updated elsewhere and the output can be downloaded easily as a .csv

I was using this, which will work for only the Top Dish per Restaurant:

=BYROW(UNIQUE('Full List'!A2:A),LAMBDA(rest_name,QUERY('Full List'!$A$2:$C,"SELECT * where Col1 matches '"&rest_name&"' order by Col3 limit 1",0)))

Given this Full List Table: Range A1:C26 of 'Full List'

The goal is a single table using a single formula to output Top 3 Dishes per Restaurant. The Full List is where a different source would come in, so some weeks might have more or less Restaurants, and more Columns might be included in the future, likely to change the Order By priorities.

I've only used BYROW to do things like SUM() a row or use XLOOKUP() with ARRAYFORMULA(), but I haven't tried returning multiple rows like this like this. Ideas?

I have tried VSTACK, ARRAYFORUMLA, but got the closest with that BYROW you see.


Solution

  • Try this out:

    =REDUCE(
       TOCOL(,1),
       UNIQUE('Full List'!A2:A),
       LAMBDA(result, rest_name, 
         VSTACK(
           result, 
           QUERY('Full List'!A2:C, "where Col1 matches '"&rest_name&"' order by Col3 limit 3", 0)
         )
       )
     )
    

    See REDUCE