我想做一个返回任意行数的查询,其中包含avg(value)和avg(created)。分组函数是创建的顺序,意味着如果我要求2行,我应该根据创建的第一行获得一个集合。
我有下表:
create table log(value int,created timestamp);
insert into log values
(1,'2016-01-01 00:00:00'),
(2,'2016-01-01 01:00:00'),
(3,'2016-01-01 02:00:00'),
(4,'2016-01-01 03:00:00'),
(5,'2016-01-01 04:00:00'),
(6,'2016-01-01 05:00:00'),
(7,'2016-01-01 06:00:00'),
(8,'2016-01-01 07:00:00'),
(9,'2016-01-01 08:00:00');
http://sqlfiddle.com/#!9/b9a94
我想要检索3行应该是
2-2016-01-01 01:00:00
5-2016-01-01 04:00:00
8-2016-01-01 07:00:00
可以在不使用java或php处理的情况下在单个查询中执行此操作吗?
答案 0 :(得分:1)
例如,当您按3分组时,按创建日期排序。您可以将3更改为要分组的大小。
SELECT avg(sub.value), avg(sub.created)
from (
SELECT @row_number:=@row_number+1 AS row_number,value, created
FROM log, (SELECT @row_number:=0) AS t
ORDER BY created
) sub
group by floor((sub.row_number-1)/3)
如果您总是希望根据行数划分为3组,您可以执行以下操作:
SELECT avg(sub.value), avg(sub.created)
from (
SELECT @row_number:=@row_number+1 AS row_number, floor((@row_number-1)/c.num) groupid,value, created
FROM log,
(SELECT @row_number:=0) AS t,
(SELECT ceil(COUNT(*)/3) num FROM log) c
ORDER BY log.created
) sub
GROUP BY sub.groupid