MySQL分组限制查询

时间:2009-08-10 15:33:19

标签: 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)
);

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

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

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

1 个答案:

答案 0 :(得分:3)

您可以使用子查询来确定每个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表示您转到查询的第五条记录,然后只选择一行。有关LIMITOFFSET的更多信息,请查看MySQL docs