我想为每个位置选择最受欢迎的菜单项。有什么建议??
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
答案 0 :(得分:2)
也许这......获得每个城市和菜单项名称的最大金额。返回顶部返回1行而不是每组一行。你需要使用max aggregate来按照你想要的方式工作。
你不能加倍聚合最大值(总和(数量)),所以你必须使用子选择,或使用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;