2016-09-15 51 views
0

我有一个表Mysql的自联接数据

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应该是分销商的所有产品1。如果分销商2没有该产品,则应该为空。

我已经尝试过与自我连接没有任何成功。 谢谢。

+0

你没有PRIMARY KEY。目前,这个问题是不可解的 - 除非第4行是错误的 – Strawberry

回答

1

没有测试过,但我认为这应该工作:

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 
+0

感谢您的回复,但在输出的第3行我得到了distributor2 id为null,因为没有记录的distributor_id 4和product_id 3。 –

+0

是的这是预期的产出,你想要什么? – apomene