2011-04-14 22 views
0

我想構建一個單一的查詢(或儘可能少)來分組數據集。所以給定了一些桶,我想返回基於特定列的結果。基於等值列值查詢分段結果

所以給出一列叫做分數這是一個雙重包含:

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
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:[email protected]+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:[email protected]+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:[email protected]+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)) 
+0

啊。這是非常接近,但給2它應該返回2行,3它應該返回3行。這個想法是,你不知道表中有多少行或列中值的分佈。 – Dave 2011-04-14 22:10:27

+0

請原諒我,但我不明白。 :( – 2011-04-14 22:29:31

+0

我已經添加了另一個查詢,希望我能理解。:) – 2011-04-14 22:58:03