使用相关子查询和MAX

时间:2013-02-08 02:26:26

标签: sql max correlated-subquery

我有两张桌子:

  

InventoryPart

     

PartNumber ,PartDescription,CategoryID,EOQ,StockPrice,   ReorderLevel,StockLevel,StockOnOrder,Weight

  

CustOrderLine

     

OrderID, PartNumber ,UnitPrice,OrderQuantity,折扣,状态

我只需要返回每个类别中最昂贵的库存件的PartNumber,PartDescription,StockPrice和CategoryID

这是迄今为止我提出的最好的......

SELECT IP.PartNumber, IP.PartDescription, IP.CategoryID, IP.StockPrice
FROM InventoryPart IP, CustOrderLine COL
WHERE IP.PartNumber = COL.PartNumber
AND COL.UnitPrice IN
  (SELECT MAX(COL.UnitPrice)
   FROM CustOrderLine COL)

此代码的问题在于它返回所有类别的MAX UnitPrice,而不是按类别分隔

我一直坚持这个问题几个小时,我觉得我现在弊大于利。我非常感谢你的帮助。

2 个答案:

答案 0 :(得分:1)

这样的事情应该使用子查询来获得与每个CategoryId相关联的MAX UnitPrice。

SELECT DISTINCT IP.*
FROM InventoryPart IP
   JOIN CustOrderLine COL ON IP.PartNumber = COL.PartNumber
   JOIN (
    SELECT IP.CategoryID, MAX(COL.UnitPrice) MaxPrice
    FROM InventoryPart IP INNER JOIN
        CustOrderLine COL ON IP.PartNumber = COL.PartNumber
    GROUP BY IP.CategoryID
   ) T ON IP.CategoryId = T.CategoryId AND COL.UnitPrice = T.MaxPrice

这是一个缩小的Fiddle,显示每个类别的单位价格最高的广告资源部分。

祝你好运。

答案 1 :(得分:1)

这是一个简单的版本。

SELECT  a.PartNumber, a.PartDescription, a.CategoryID, a.StockPrice
FROM    InventoryPart a
        INNER JOIN
        (
            SELECT  PartNumber, MAX(StockPrice) max_price
            FROM    Inventorypart
            GROUP   BY PartNumber
        ) b ON  a.partNumber = b.PartNumber AND
                a.StockPrice = b.max_price

为了获得更好的效果,请在列INDEX

上添加(PartNumber, StockPrice)
ALTER TABLE InventoryPart ADD INDEX (PartNumber, StockPrice)

更新1

SELECT  a.PartNumber, a.PartDescription, a.CategoryID, a.StockPrice
FROM    InventoryPart a
        INNER JOIN
        (
            SELECT  PartNumber, CategoryID, MAX(StockPrice) max_price
            FROM    Inventorypart
            GROUP   BY PartNumber, CategoryID
        ) b ON  a.partNumber = b.PartNumber AND
                a.StockPrice = b.max_price AND
                a.CategoryID = b.CategoryID

ALTER TABLE InventoryPart ADD INDEX (PartNumber, StockPrice, CategoryID)