分组按指定的有序行数

时间:2011-08-11 13:04:22

标签: 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的平均价格。我想计算按日期为指定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

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

提前致谢。

4 个答案:

答案 0 :(得分: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)

答案 1 :(得分:0)

也许你可以使用

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

=转换为秒,除以秒数3天,然后向下舍入

答案 2 :(得分: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

答案 3 :(得分:0)

SELECT AVG( price ) FROM my_table
    GROUP BY ( date - ( SELECT MIN( date ) FROM my_table WHERE fid = 1 ) ) DIV 3
    WHERE fid = 1