gpt4 book ai didi

Mysql自连接数据

转载 作者:行者123 更新时间:2023-11-29 11:17:25 25 4
gpt4 key购买 nike

我有一张 table

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

关于Mysql自连接数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39505627/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com