DB2 使用 group by 选择最大行
DB2 Selecting maximum row with group by
我在 DB2 数据库中有以下表格:
Products(Category, VendorId, Price)
Vendor(VendorId, Name)
我现在正尝试在 SQL 中制定以下查询:
For all categories select the Category, Price and Vendor Id and Vendor Name where
Price is the highest in the Category.
我可以使用
轻松获得每个类别的最高价格
SELECT Category, max(Price) FROM Products GROUP BY Category
但是我无法将 VendorId 添加到 SELECT,因为这会给我一个错误 -119,根据手册,这意味着
A COLUMN OR EXPRESSION IN A HAVING CLAUSE IS NOT VALID
但我没有在查询中使用 HAVING。制定上述查询的正确方法是什么?
为此使用row_number(),如下:
select
pv.Category, pv.Price, pv.VendorId, pv.Name
from (
select
p.Category, p.Price, p.VendorId, v.Name
, ROW_NUMBER() OVER(PARTITON BY p.Category ORDER BY p.Price DESC) as rowno
from Products p
inner join Vendor v ON p.VendorId = v.VendorId
) pv
where pv.rowno = 1
此方法允许您定位包含每个类别中最高价格的整行。它对于 "the latest order from each client"
这样的东西也很有用
请注意,如果您有多个产品满足 "maximum price per category" 条件并且您希望结果中包含所有这些行,请使用 RANK() 或 DENSE_RANK() 而不是 ROW_NUMBER()
我在 DB2 数据库中有以下表格:
Products(Category, VendorId, Price)
Vendor(VendorId, Name)
我现在正尝试在 SQL 中制定以下查询:
For all categories select the Category, Price and Vendor Id and Vendor Name where Price is the highest in the Category.
我可以使用
轻松获得每个类别的最高价格SELECT Category, max(Price) FROM Products GROUP BY Category
但是我无法将 VendorId 添加到 SELECT,因为这会给我一个错误 -119,根据手册,这意味着
A COLUMN OR EXPRESSION IN A HAVING CLAUSE IS NOT VALID
但我没有在查询中使用 HAVING。制定上述查询的正确方法是什么?
为此使用row_number(),如下:
select
pv.Category, pv.Price, pv.VendorId, pv.Name
from (
select
p.Category, p.Price, p.VendorId, v.Name
, ROW_NUMBER() OVER(PARTITON BY p.Category ORDER BY p.Price DESC) as rowno
from Products p
inner join Vendor v ON p.VendorId = v.VendorId
) pv
where pv.rowno = 1
此方法允许您定位包含每个类别中最高价格的整行。它对于 "the latest order from each client"
这样的东西也很有用请注意,如果您有多个产品满足 "maximum price per category" 条件并且您希望结果中包含所有这些行,请使用 RANK() 或 DENSE_RANK() 而不是 ROW_NUMBER()