gpt4 book ai didi

sql - MySQL分组限制查询

转载 作者:行者123 更新时间:2023-11-29 05:46:27 24 4
gpt4 key购买 nike

假设我有一张 table :

create table foo (
corp_id int not null,
tdate date not null,
sec_id int unsigned not null,
amount int unsigned not null,
primary key (corp_id, sec_id, tdate)
);

以下查询将返回所有 corp_id 和日期的金额列的总和:

select corp_id, tdate, sum(amount) from foo group by corp_id, tdate;

我现在如何限制此查询以仅返回每个 corp_id 的前 5 个最新日期?

最佳答案

您可以使用子查询来确定每个 corp_id 的第五个日期:

select
corp_id,
tdate,
sum(amount)
from
foo f
where
tdate >=
(select tdate
from foo
where corp_id = f.corp_id
order by tdate desc
limit 1 offset 4)

limit 1 offset 4 意味着您转到查询的第五条记录,然后只选择一行。查看MySQL docs有关 LIMITOFFSET 的更多信息。

关于sql - MySQL分组限制查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1255591/

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