分组按指定的有序行数

Mar*_*cin 5 mysql group-by sql-order-by limit

我的MySQL数据库中有这样的表:

---------------------------
|fid | price | date       |
---------------------------
|  1 | 1.23  | 2011-08-11 |
|  1 | 1.43  | 2011-08-12 |
|  1 | 1.54  | 2011-08-13 |
|  1 | 1.29  | 2011-08-14 |
|  1 | 1.60  | 2011-08-15 |
|  1 | 1.80  | 2011-08-16 |
Run Code Online (Sandbox Code Playgroud)

fid- 这是产品ID
price- 这是指定日期内产品的价格

我想计算产品的平均价格fid=1.我想计算n=3按日期排序的第一行的平均价格fid,然后计算按日期排序的另外3行的平均价格.

如何分组前3行并计算平均值,然后将下3行分组并计算平均值.在计算之前,我需要按日期对行进行排序,然后对行进行分组n.

如果n=3这应该返回这样的结果:

--------------
|fid | price |
--------------
|  1 | 1.40  | 2011-08-11 -> 2011-08-13 - average price for 3 days
|  1 | 1.56  | 2011-08-14 -> 2011-08-16 - average price for 3 days
Run Code Online (Sandbox Code Playgroud)

如何创建SQL Query来进行此类计算?

提前致谢.

Nic*_*ssu 2

不幸的是,mysql 不提供像 oracle、mssql 和 postgres 那样的分析功能。所以你必须利用变量来实现你的目标。

create table mytest (
id int not null auto_increment primary key,
fid int,
price decimal(4,2),
fdate date
) engine = myisam;

insert into mytest (fid,price,fdate)
values 
(1,1.23,'2011-08-11'),
(1,1.43,'2011-08-12'),
(1,1.54,'2011-08-13'),
(1,1.29,'2011-08-14'),
(1,1.60,'2011-08-15'),
(1,1.80,'2011-08-16');


select 
concat_ws('/',min(fdate),max(fdate)) as rng,
format(avg(price),2) as average from (
select *,@riga:=@riga+1 as riga
    from mytest,(select @riga:=0) as r order by fdate
     ) as t
group by ceil(riga/3);


+-----------------------+---------+
| rng                   | average |
+-----------------------+---------+
| 2011-08-11/2011-08-13 | 1.40    |
| 2011-08-14/2011-08-16 | 1.56    |
+-----------------------+---------+
2 rows in set (0.02 sec)
Run Code Online (Sandbox Code Playgroud)