如果使用MAX或MIN聚合函数,如何从一组记录中选择适当的记录/记录,以便记录/记录与聚合函数返回的值匹配?
我需要使用NorthWind.products数据库表(http://www.zentut.com/wp-content/uploads/downloads/2013/06/Northwind-Sample-Database-Diagram.pdf)才能找到每个类别中最昂贵的产品。到目前为止,我尝试了两种变体:
SELECT CategoryID, ProductID, ProductName, MAX(UnitPrice) MostExpensive
FROM [NORTHWND].[dbo].[Products] as A
GROUP BY CategoryID;
此代码产生错误“Column'NORTHWND.dbo.Products.ProductID'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。”我完全理解这个原因。没关系。
第二个变种是:
SELECT CategoryID, ProductID, ProductName
FROM [NORTHWND].[dbo].[Products] as A
WHERE UnitPrice = (
SELECT MAX(UnitPrice) FROM [NORTHWND].[dbo].[Products] AS B GROUP BY CategoryID HAVING A.CategoryID = B.CategoryID
)
这个工作正常,返回的记录是正确的,但我想在第一个SELECT中有4列,第四个应该是每个类别中的最高价格。我可以更改SQL查询以实现该目标,还是应该尝试第三种变体?
答案 0 :(得分:2)
SQL Server >= 2005
:
SELECT *
FROM (
SELECT CategoryID,
ProductID,
ProductName,
UnitPrice,
RowNum = ROW_NUMBER() OVER (PARTITION BY CategoryID ORDER BY UnitPrice DESC)
FROM dbo.Products
) t
WHERE t.RowNum = 1
SQL Server < 2005
:
SELECT DISTINCT
p.CategoryID,
p.ProductID,
p.ProductName,
p.UnitPrice
FROM dbo.Products p
JOIN (
SELECT CategoryID, UnitPrice = MAX(UnitPrice)
FROM dbo.Products
GROUP BY CategoryID
) t ON t.UnitPrice = p.UnitPrice AND t.CategoryID = p.CategoryID