我正在运行以下SQL查询,以选择https://www.w3schools.com/sql/trysql.asp中每个产品类别中价格最高的产品
SELECT p.ProductID, p.productName, p.Price, p.CategoryID, c.CategoryName
FROM [Categories] c
LEFT JOIN [Products] p
ON (c.CategoryID = p.CategoryID)
WHERE Price IN (SELECT Max(Price) FROM Products GROUP BY CategoryID)
ORDER BY p.CategoryID
但是,对于某些类别(例如类别3和4),生成的输出给出2个结果。为什么会这样?以及如何修改代码以使每个代码仅获得最高结果?另外,如何使每个类别的价格都最低?
答案 0 :(得分:1)
使用row_number()
slect a.* from (SELECT p.ProductID, p.productName, p.Price, p.CategoryID, c.CategoryName,
row_number()over(partition by p.CategoryID order by p.Price desc) rn
FROM [Categories] c
LEFT JOIN [Products] p
ON c.CategoryID = p.CategoryID
) a where a.rn=1
答案 1 :(得分:1)
APPLY
可能是最简单的方法:
SELECT p.ProductID, p.productName, p.Price, p.CategoryID, c.CategoryName
FROM categories c OUTER APPLY
(SELECT TOP (1) p.*
FROM Products p
WHERE p.CategoryID = c.CategoryID
ORDER BY p.Price DESC
) p
ORDER BY c.CategoryID