Select top 1 from each group sql
Asked By: Jeffrey Grima
Originally Asked On: 2014-01-02 12:58:08
Asked Via: stackoverflow
I want to select the most popular menu item per location. Any suggestions??
SELECT a.City, a.ItemName, a.Quantity FROM (SELECT TOP 1 l.city AS City, mi.name AS ItemName, SUM(ft.quantity_sold) AS Quantity FROM FactTable ft JOIN MenuItem mi ON (ft.menuItemID = mi.ID) JOIN Location l ON (ft.locationID = l.ID) ORDER BY Quantity DESC GROUP BY l.city, mi.name; ) AS a
He received 1 answers
eventually accepting:
xQbert’s answer to
Select top 1 from each group sql
Maybe this… get the maximum sum for each city and menu item name. Top returns 1 row not one row per group. you need to use the max aggregate to make this work the way you want.
you can’t double aggregate max(sum(Quantity)) so you have to either use a sub select, or use a CTE (common table expression). This is the subselect.
Select city, itemName, max(Quantity) FROM ( SELECT l.city AS City, mi.name AS ItemName, SUM(ft.quantity_sold) AS Quantity FROM FactTable ft JOIN MenuItem mi ON (ft.menuItemID = mi.ID) JOIN Location l ON (ft.locationID = l.ID) GROUP BY l.city, mi.name) sub GROUP BY City, ItemName;
If the selected answer did not help you out, the other answers might!
All Answers For: Select top 1 from each group sql
xQbert’s answer to
Select top 1 from each group sql
Maybe this… get the maximum sum for each city and menu item name. Top returns 1 row not one row per group. you need to use the max aggregate to make this work the way you want.
you can’t double aggregate max(sum(Quantity)) so you have to either use a sub select, or use a CTE (common table expression). This is the subselect.
Select city, itemName, max(Quantity) FROM ( SELECT l.city AS City, mi.name AS ItemName, SUM(ft.quantity_sold) AS Quantity FROM FactTable ft JOIN MenuItem mi ON (ft.menuItemID = mi.ID) JOIN Location l ON (ft.locationID = l.ID) GROUP BY l.city, mi.name) sub GROUP BY City, ItemName;
Of course, you should really check out the original question.
The post Select top 1 from each group sql [ANSWERED] appeared first on Tech ABC to XYZ.