gpt4 book ai didi

mysql - 将表与其自身连接

转载 作者:行者123 更新时间:2023-11-29 21:14:27 25 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 |

谁能帮我?

最佳答案

使用相关子查询:

select h.*,
(select avg(h2.transaction)
from history h2
where h2.id = h.id
) as avg_trans
from history h;

您还可以使用分组依据来执行此操作。但是,上面可以利用 history(id, transaction) 上的索引。另请注意,SQL 有内置聚合函数 AVG(),因此您不妨使用它。

group by/join 版本如下:

select h.*, hh.avg_trans
from history h join
(select id, avg(h2.transaction) as avg_trans
from history h2
where h2.id = h.id
) hh
on h.id = hh.id;

关于mysql - 将表与其自身连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36083073/

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