假设我有一张桌子:
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个最新日期?
发布于 2009-08-10 15:36:51
您可以使用子查询来确定每个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意味着您转到查询的第五条记录,然后只选择一行。有关LIMIT和OFFSET的更多信息,请查看MySQL docs。
https://stackoverflow.com/questions/1255591
复制相似问题