基于等值列值的查询结果查询

时间:2011-04-14 21:16:56

标签: mysql

我想构建一个查询(或尽可能少)来对数据集进行分组。所以给定了一些桶,我想根据特定的列返回结果。

因此给出了一个名为score的列,它是一个包含以下内容的双精度:

 90.00
 91.00
 94.00
 96.00
 98.00
 99.00

我希望能够将GROUP BY子句与以下函数一起使用:

SELECT MIN(得分),MAX(得分),SUM(得分)FROM表GROUP BY BUCKETS(得分,3)

理想情况下,这将返回3行(将结果分组为3个桶,每个组中的数量尽可能接近相等):

 90.00, 91.00, 181.00
 94.00, 96.00, 190.00
 98.00, 99.00, 197.00

是否有某些功能可以做到这一点?我想避免返回所有行并自己弄清楚桶段。

戴夫

1 个答案:

答案 0 :(得分:1)

create table test (
id int not null auto_increment primary key,
val decimal(4,2)
) engine = myisam;

insert into test (val) values 
 (90.00),
 (91.00),
 (94.00),
 (96.00),
 (98.00),
 (99.00);

select min(val) as lower,max(val) as higher,sum(val) as total from (
select id,val,@row:=@row+1 as row
from test,(select @row:=0) as r order by id
) as t
group by ceil(row/2)

+-------+--------+--------+
| lower | higher | total  |
+-------+--------+--------+
| 90.00 |  91.00 | 181.00 |
| 94.00 |  96.00 | 190.00 |
| 98.00 |  99.00 | 197.00 |
+-------+--------+--------+
3 rows in set (0.00 sec)

不幸的是,mysql没有像rownum()这样的分析函数,所以你必须使用一些变量来模拟它。完成后,您可以简单地使用ceil()函数,以便根据需要对每个行进行分组。希望尽管我的英语很有帮助。

set @r = (select count(*) from test);
select min(val) as lower,max(val) as higher,sum(val) as total from (
select id,val,@row:=@row+1 as row
from test,(select @row:=0) as r order by id
) as t
group by ceil(row/ceil(@r/3))

或使用单个查询

select min(val) as lower,max(val) as higher,sum(val) as total from (
select id,val,@row:=@row+1 as row,tot
from test,(select count(*) as tot from test) as t2,(select @row:=0) as r order by id
) as t
group by ceil(row/ceil(tot/3))