2017-02-09 143 views
0

我有這樣一個表: Table1 ,我需要一個列到表中添加的平均交貨時間 avr_del_time column added 我的代碼是:添加平均列到同一個表

SELECT a.vendor, a.part_nr, a.delivery_time, b.avr_del_time 
FROM Table1 a 
INNER JOIN (SELECT AVG(delivery_time) AS avr_del_time FROM Table1 GROUP BY vendor, part_nr) b 
ON a.vendor = b.vendor, a.part_nr=b.part_nr 

請指導我。 ..

回答

0

您需要返回聯接字段在子查詢或連接將無法工作

SELECT a.vendor, a.part_nr, a.delivery_time, b.avr_del_time 
FROM Table1 a 
INNER JOIN (SELECT Vendor, 
        part_nr, 
        AVG(delivery_time) AS avr_del_time 
      FROM Table1 
      GROUP BY vendor, part_nr) b 
ON a.vendor = b.vendor and a.part_nr=b.part_nr 
0

沒有看到任何問題與您發佈的代碼,除了JOIN ON條件即應

ON a.vendor = b.vendor 
AND a.part_nr=b.part_nr // OR condition can as well be based on requirement 

而且因爲它是一個計算值,在加單獨的列到你的表是沒有意義的,而有列在您的顯示結果同時從表

1

您的查詢是在正確的軌道上。你只需要修復了SQL錯誤:

SELECT a.vendor, a.part_nr, a.delivery_time, b.avr_del_time 
FROM Table1 as a INNER JOIN 
     (SELECT vendor, part_nr, AVG(delivery_time) AS avr_del_time 
     FROM Table1 
     GROUP BY vendor, part_nr 
    ) as b 
    ON a.vendor = b.vendor AND a.part_nr = b.part_nr; 

注:

  • GROUP BY子查詢,則需要在SELECT鍵。
  • 您在ON條件中有一個逗號;它應該是AND
  • 我建議您使用表名稱的縮寫表別名。