Mysql Q:高效地获取大表中最早的值、最近的值和每组计数?
我希望提高我的查询性能/或更高效的查询设计,以获得mysql表中每个组的最小值、最大值和计数 我需要的输出是:Mysql Q:高效地获取大表中最早的值、最近的值和每组计数?,mysql,sql,Mysql,Sql,我希望提高我的查询性能/或更高效的查询设计,以获得mysql表中每个组的最小值、最大值和计数 我需要的输出是: +---------+----------+----------+-----+ | id | f_amount | r_amount | cnt | +---------+----------+----------+-----+ | 1 | 1000 | 200 | 3 | | 2 | 300 | 300 |
+---------+----------+----------+-----+
| 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 t.fund_id, tf.amount as first_amount, tl.amount as last_amount, t.cnt
from (select t.fund_id, min(dt) as min_dt, max(dt) as max_dt, count(*) as cnt
from trans t
group by t.fund_id
) t join
trans tf
on tf.fund_id = t.fund_id and tf.dt = min_dt join
trans tl
on tl.fund_id = t.fund_id and tl.dt = max_dt;
是一个数据库管理员。查看您的代码和数据。。看来你需要
SELECT fund_id, Max(amount) , min(amount), count(*)
FROM trans
group by fund_id
没问题,我现在注意到,MAX(dt)
,MIN(dt)
也应该编辑为MAX | MIN(amount)
。