gpt4 book ai didi

mysql - 选择 Join table with table self

转载 作者:行者123 更新时间:2023-11-29 01:53:07 24 4
gpt4 key购买 nike

我有问题...

Table : history
|id |transaction|created_at |merchant_id|
|-----|-----------|-------------------|-----------|
|1 |400 |2015-10-12 11:08:37|33 |
|1 |500 |2015-10-15 09:38:22|33 |
|1 |600 |2015-10-21 14:47:12|22 |
|2 |100 |2015-09-26 10:48:27|31 |
|2 |500 |2015-09-30 11:18:07|27 |
|2 |300 |2015-10-02 17:33:57|31 |

我想在我查询时:

SELECT SUM(a.transaction)/COUNT(a.transaction) AS avg_trans
FROM history AS a GROUP BY a.id, a.merchant_id

Result:
|id |avg_trans|merchant_id|
|------|---------|-----------|
|1 |450 |33 |
|1 |600 |22 |
|2 |200 |31 |
|2 |500 |27 |

然后将 avg_trans 显示到表格历史记录中,如下所示:

|id   |transaction|created_at         |avg_trans|merchant_id|
|-----|-----------|-------------------|---------|-----------|
|1 |400 |2015-10-12 11:08:37|450 |33 |
|1 |500 |2015-10-15 09:38:22|450 |33 |
|1 |600 |2015-10-21 14:47:12|600 |22 |
|2 |100 |2015-09-26 10:48:27|200 |31 |
|2 |200 |2015-09-30 11:18:07|500 |27 |
|2 |300 |2015-10-02 17:33:57|200 |31 |

谁能帮帮我?

最佳答案

正如@Strawberry 指出的那样,您需要使用子查询来计算 id 和商家 id 的平均值,并将其加入到您的主表中:

select t1.*, t2.avg_trans
from table t1
inner join (select id, merchant_id, avg(transaction) avg_trans
from table
group by id, merchant_id) t2 on t1.id=t2.id and t1.merchant_id=t2.merchant_id

关于mysql - 选择 Join table with table self,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36096369/

24 4 0