我目前使用的是 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) = */
最佳答案
您不需要 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
如果您想要所有行的最佳利润平局,请使用此
SELECT TOP 1 WITH TIES ItemType,
SUM((Price - CostToMake) * Monthly Sales) AS BestMonthlyProfit
FROM Menu
GROUP BY ItemType
ORDER BY BestMonthlyProfit DESC
关于SQL - 限制和排序数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34835114/