我目前正在使用Microsoft SQL Server 2012
我希望回答一个问题"检索从月度销售中获得最佳利润的单个ItemType?"
当我运行下面的前3行代码时,我会返回3行数据,其中包含两列(ItemType,BestMonthlyProfit)。我目前正在尝试取回一行结果,我知道我必须创建一个HAVING语句来执行此操作,但我仍然坚持使用语法。不确定它是否涉及某种MAX语句。如果有人可以帮助我,我们将不胜感激。
这是我得到的(我在下面评论了我的HAVING声明,但我认为它已经接近了):
SELECT
ItemType,
SUM((Price - CostToMake) * Monthly Sales) AS BestMonthlyProfit
FROM Menu
GROUP BY ItemType
/* HAVING SUM((Price - CostToMake) * Monthly Sales) = */
答案 0 :(得分:3)
您不需要Having
条款将TOP 1
与Order by
一起使用。
SELECT TOP 1 ItemType,
SUM((Price - CostToMake) * Monthly Sales) AS BestMonthlyProfit
FROM Menu
GROUP BY ItemType
ORDER BY BestMonthlyProfit DESC
如果您希望在最佳利润中存在 tie 时所有行,请使用此
SELECT TOP 1 WITH TIES ItemType,
SUM((Price - CostToMake) * Monthly Sales) AS BestMonthlyProfit
FROM Menu
GROUP BY ItemType
ORDER BY BestMonthlyProfit DESC