SQL:如何找到特定商品的MAX值/价格?

时间:2017-10-22 03:39:07

标签: sql sql-server

我是SQL新手,想知道是否有人可以指导我。 这是我的代码和表输出: Code

低于2.25的价格正在出现。我只想要2.25(最高)值。 我已经尝试在select语句中删除MAX,删除分组,并用

替换WHERE语句
WHERE Price = (
    SELECT MAX(Price) 
    FROM tblPurchaseOrderLine
    ) 
AND tblProduct.Description LIKE 'Alpine Small Pot'

buuut它没有输出。

SOLUTION:

SELECT      tblPurchaseOrder.PONumber 'PO Number',
            tblVendor.Name 'Vendor Name',
            tblProduct.ProductID 'Product ID',
            tblProduct.Description,
            MAX(tblPurchaseOrderLine.Price)'Price'
FROM        tblPurchaseOrder
INNER JOIN  tblVendor
ON          tblVendor.VendorID = tblPurchaseOrder.VendorID
INNER JOIN  tblPurchaseOrderLine
ON          tblPurchaseOrderLine.PONumber = tblPurchaseOrder.PONumber
INNER JOIN  tblProduct
ON          tblProduct.ProductID = tblPurchaseOrderLine.ProductID
WHERE       Price = (SELECT MAX(Price) 
            FROM tblPurchaseOrderLine
            WHERE tblProduct.ProductID = tblPurchaseOrderLine.ProductID)
            AND tblProduct.Description LIKE 'Alpine Small Pot'
GROUP BY    tblPurchaseOrder.PONumber,tblVendor.Name,tblProduct.ProductID,tblProduct.Description

谢谢!我搞定了

1 个答案:

答案 0 :(得分:0)

你想要的是一个相关的子查询:

from tblPurchaseOrderLine t1
WHERE Price = (
    SELECT MAX(Price) 
    FROM tblPurchaseOrderLine t2
    where t1.product_id = t2.product_id
    ) 
AND tblProduct.Description LIKE 'Alpine Small Pot'

有一种更好的方法:

你可以使用带有窗口功能的TOP 1来执行此操作:

select top 1 with ties t.*
from your_table t
where tblProduct.Description LIKE 'Alpine Small Pot'
order by row_number() over (
        partition by product_id
        order by price desc
        );