2017-10-22 117 views
0

我是新来的SQL,并想知道如果有人能指导我。 这里是我的代码和表格输出: CodeSQL:如何找到特定项目的最大价值/价格?

价格低于2.25出现。我只想要2.25(最高)的值。 我试过在SELECT语句中移除MAX,删除分组,并与

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

更换WHERE语句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 

谢谢!我得到它的工作

+0

尝试删除AND部分以查看描述标准是否是原因 –

回答

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,在窗口功能order clause:

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 
     );