2014-12-02 57 views
0

我試圖加入2個表並創建一個返回產品最低價值的新字段。我嘗試了很多變化,似乎無法讓它工作。列表供應商和最低價產品SQL

SELECT DISTINCT VENDOR.*, PRODUCT.P_PRICE, PRODUCT.LOWEST_PRICE AS MIN(PRODUCT.P_PRICE) 
FROM PRODUCT 
INNER JOIN VENDOR 
ON VENDOR.V_CODE = PRODUCT.V_CODE 
ORDER BY VENDOR.V_NAME 
+0

PRODUCT.LOWEST_PRICE與MIN(PRODUCT.P_PRICE)看起來是錯誤的。嘗試MIN(PRODUCT.P_PRICE)AS LOWEST_PRICE – 2014-12-02 23:50:24

回答

1

你可以使用這個,這將從最低價格供應商的產品訂購

SELECT VENDOR.V_NAME, MIN(PRODUCT.P_PRICE) AS LOWEST_PRICE 
FROM VENDOR 
INNER JOIN PRODUCT 
ON VENDOR.V_CODE = PRODUCT.V_CODE 
GROUP BY VENDOR.V_NAME 
ORDER BY LOWEST_PRICE 

SQL FIDDLE: - http://sqlfiddle.com/#!3/467c8/2

1

如果你是供應商,使用GROUP BY和分鐘尋找最低價格:

SELECT VENDOR.V_NAME, MIN(PRODUCT.P_PRICE) AS LOWEST_PRICE 
FROM PRODUCT 
INNER JOIN VENDOR 
ON VENDOR.V_CODE = PRODUCT.V_CODE 
GROUP BY VENDOR.V_NAME 
ORDER BY VENDOR.V_NAME 
0

不知道你的架構是如何定義試試這個:

SELECT 
    VENDOR.V_NAME, 
    PRODUCT.P_PRICE AS [VENDOR PRICE], 
    MIN(PRODUCT.P_PRICE) AS [LOWEST PRICE] 
FROM 
    PRODUCT 
    INNER JOIN VENDOR ON VENDOR.V_CODE = PRODUCT.V_CODE 
GROUP BY 
    VENDOR.V_NAME,PRODUCT.P_PRICE 
ORDER BY 
    VENDOR.V_NAME 
+0

剪下一個原始代碼的快速粘貼,修復它,沒有抓住它 – 2014-12-02 23:49:08

+0

此外,您的括號中承擔sql服務器,但它沒有標記爲這樣。 – paqogomez 2014-12-02 23:49:39

+0

我的法語很差,但我覺得這句話很有趣。我自己又一個假設。大聲笑 – 2014-12-02 23:51:03

0

如果你想每個供應商的價格最低的產品,我會建議使用窗口功能:

select pv.* 
from (select v.v_name, p.p_name, p.p_price 
      row_number() over (partition by p.v_code order by p.p_price asc) as seqnum 
     from vendor v join 
      product p 
      on v.v_code = p.v_code 
    ) pv 
where seqnum = 1 
相關問題