Mysql 按指定数量的有序行分组

Mysql 按指定数量的有序行分组,mysql,group-by,sql-order-by,limit,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

我的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
价格
-这是指定日期内产品的价格

我想计算产品的平均价格
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查询来执行此类计算

提前谢谢。

也许你可以

GROUP BY FLOOR(UNIX_TIMESTAMP(date)/(60*60*24*3))

=转换为秒数,除以秒数3天,然后取整

不幸的是,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)

如果日期中有一个“洞”,即缺少某一天,该怎么办?@Tomas如果有“洞”,则缺少的日期的值将被删除。但您的解决方案不会将3个连续的日期分组,因为您是按日期的值分组的。如果日期中有一个“洞”,该怎么办,例如,缺少某一天?然后它计算出3(真实)天的2个现有价格的平均值,但这不是询问者想要的,好吧(如果日期更稀疏,它将仅平均1个价格),这很好。我不知道在哪里声明变量。现在我看到它是通过select@riga:=0在子查询中声明的。回答得很好。非常感谢你
select fid, avg(price), min(date), max(date)
from
    (select floor((@rownum := @rownum + 1)/3) as `rank`,  prices.*
    from prices, (SELECT @rownum:=-1) as r
    order by date) as t
group by rank
SELECT AVG( price ) FROM my_table
    GROUP BY ( date - ( SELECT MIN( date ) FROM my_table WHERE fid = 1 ) ) DIV 3
    WHERE fid = 1