mysql - 按指定数量的有序行分组

标签 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 |

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/

相关文章:

mysql - 需要获取最近 10 个活跃主题的用户

mysql - 返回尚未关注(或查看)的最受关注用户

mysql - 将两个表组合在一起以获得所有列,但我需要单独的数据行而不是一行

mysql - 如何使用group by sql更新集合

mysql - MySQL 中的 "Invalid use of group function"

mysql - 计算多列的分组

java - 使用Hibernate 'order by' 具有表达式(sum,max,...)的列?

mysql - 如何对mysql中显示的内容进行升序或降序显示

MySQL 左连接带有子 IsDeleted 标志

php - 使用 session 变量来区分网站用户的类型,例如管理员或成员(member)