小编典典

从每个组SQL中选择前1个

sql

我想选择每个位置最受欢迎的菜单项。有什么建议??

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

阅读 144

收藏
2021-04-22

共1个答案

小编典典

也许这…获得每个城市和菜单项名称的最大和。顶部返回1行,而不是每组一行。您需要使用最大聚合来使此工作按您想要的方式进行。

您不能将合计的max(sum(Quantity))加倍,因此必须使用子选择或使用CTE(公用表表达式)。这是子选择。

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;
2021-04-22