Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/84.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
MySQL分组限制查询_Sql_Mysql - Fatal编程技术网

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
表示您转到查询的第五条记录,然后只选择一行。有关
限制
偏移
的详细信息,请查看