Is there a way to combine an GROUP BY
and OBJECT_AGG
in snowflake with different levels of aggregation between the two?
In the following example, we wish to return, for each city, an object mapping cuisine
to the highest michelin stars of that cuisine in the city:
City | Restaurant | Cuisine | Michelin Stars |
---|---|---|---|
San Fransisco | Quince | Californian | 3 |
San Fransisco | Coi | Californian | 2 |
San Fransisco | Mister Jius | Chinese | 1 |
London | Le Gavroche | French | 2 |
London | La Dame de Pic | French | 2 |
London | Restaurant Gordon Ramsay | French | 3 |
We want to produce the following:
City | Cuisine to Top Rating |
---|---|
San Fransisco | {'Californian': 3, 'Chinese': 1} |
London | {'French': 3} |
My initial approach is:
SELECT
city,
OBJECT_AGG(cuisine, MAX(michelin_stars)::variant) over (partition by cuisine)
FROM
top_restaurants
GROUP BY city
This returns the error cuisine is not a valid group by expression
.
This question is similar to
From the above, I believe the cause is the GROUP BY
is calculated before the PARTITION BY
and breaks when the GROUP BY
drops cuisine
as it attempts to aggregate.
References:
https://docs.snowflake.com/en/sql-reference/functions/object_agg.html