簡體   English   中英

MySQL的自我加入數據

[英]Mysql Self join data

我有一張桌子

distributor_id | product_id | price
1              | 1          | 10.00
1              | 2          | 11.00
1              | 3          | 12.00
1              | 1          | 14.00
4              | 1          | 9.00
4              | 2          | 32.00
4              | 5          | 17.00

我想比較分銷商產品的價格,即我想獲得如下輸出:

distributor1|distributor2|product_id|distributor1_price|distributor2_price
1           | 4          | 1        |12.00             |9.00
1           | 4          | 2        |11.00             |32.00
1           | 4          | 3        |12.00             |null

distributor1_price,distributor2_price將是product_id的平均價格。 product_id應該是distributor1的所有產品。 如果distributor2沒有該產品,則應該為空。

我嘗試通過自連接進行嘗試,但沒有成功。 謝謝。

尚未測試,但我認為這應該可行:

SELECT a.distributor_id
    ,b.distributor_id
    ,a.product_id
    ,AVG(a.price)
    ,AVG(b.price)
FROM mytable AS a
LEFT JOIN mytable AS b ON a.product_id = b.product_id
GROUP BY a.product_id

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM