MySQL分组限制查询
假设我有一张桌子:MySQL分组限制查询,sql,mysql,Sql,Mysql,假设我有一张桌子: 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) ); 以下查询将返回所有公司id和日期的“金额”列的总和: select corp_id, tdate, sum(amount) from
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)
);
以下查询将返回所有公司id和日期的“金额”列的总和:
select corp_id, tdate, sum(amount) from foo group by corp_id, tdate;
现在如何限制此查询只返回每个公司id的前5个最新日期?您可以使用子查询确定每个
公司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
表示您转到查询的第五条记录,然后只选择一行。有关限制
和偏移
的详细信息,请查看