我有一张桌子
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 |nulldistributor1_price,distributor2_price将是product_id的平均价格。product_id应该是distributor1的所有产品。如果distributor2没有该产品,则应该为空。
我已经尝试了self-join,但没有成功。谢谢。
发布于 2016-09-15 15:57:58
还没有测试过,但我认为这应该是可行的:
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_idhttps://stackoverflow.com/questions/39505627
复制相似问题