2017-10-22 48 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 
     );