我的 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 |
fid
- 这是产品 ID
price
- 这是指定日期的产品价格
我想计算产品 fid=1
的平均价格。我想为指定的 fid
计算按日期排序的前 n=3
行的平均价格,然后计算按日期排序的另外 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
如何创建 SQL 查询来进行此类计算?
提前致谢。
最佳答案
不幸的是,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)
关于mysql - 按指定数量的有序行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7026366/