2009-08-10 66 views
1

说我有一个表:MySQL的GroupWise的限制查询

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个最新日期?

回答

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