SQL - 限制和排序数据

时间:2016-01-17 04:30:27

标签: sql sql-server sql-server-2012

我目前正在使用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) = */

1 个答案:

答案 0 :(得分:3)

您不需要Having条款将TOP 1Order 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