gpt4 book ai didi

mysql - Q : Efficiently get the oldest value, 大表中每组的最新值和计数?

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

我希望提高我的查询性能/或更高效的查询设计,以获取 mysql 表中每组的最小值、最大值和计数。

我需要的输出是:

+---------+----------+----------+-----+
| id | f_amount | r_amount | cnt |
+---------+----------+----------+-----+
| 1 | 1000 | 200 | 3 |
| 2 | 300 | 300 | 1 |
| 3 | 450 | 600 | 2 |
+---------+----------+----------+-----+

其中 f_amount 是最早的金额,r_amount 是最新的金额,cnt 是该特定 ID 的交易数量。

我的查询[得到了想要的结果,但速度非常慢]。我的表有近 10 亿条记录,每个 id 本身有数千个事务,所有数据都在 MySQL 中。

我无法使用公用表表达式实现相同的功能。

SELECT     x.fund_id AS id, 
min_amt AS f_amount,
max_amt AS r_amount,
z.cnt
FROM (
SELECT fund_id,
amount AS min_amt,
dt
FROM trans
WHERE dt =
(
SELECT Min(dt)
FROM trans g
WHERE g.fund_id = trans.fund_id)) x
INNER JOIN
(
SELECT fund_id,
amount AS max_amt,
dt
FROM trans
WHERE dt =
(
SELECT Max(dt)
FROM trans g
WHERE g.fund_id = trans.fund_id)) y
INNER JOIN
(
SELECT fund_id,
Count(fund_id) AS cnt
FROM trans g
GROUP BY 1) z
where x.fund_id = y.fund_id
AND x.fund_id = z.fund_id
ORDER BY x.fund_id;

表创建和示例数据插入:

CREATE TABLE trans (
fund_id int,
amount int,
dt date);



insert into trans values(1,1000,'2019-02-01');
insert into trans values(1,500,'2019-02-02');
insert into trans values(1,200,'2019-02-03');
insert into trans values(2,300,'2019-02-15');
insert into trans values(3,450,'2019-02-17');
insert into trans values(3,600,'2019-02-20');

最佳答案

查看您的代码和数据.. 似乎您需要

SELECT fund_id, Max(amount) , min(amount), count(*)
FROM trans
group by fund_id

关于mysql - Q : Efficiently get the oldest value, 大表中每组的最新值和计数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54845658/

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