2011-02-27 46 views
6

冰雹,堆疊!如何選擇按範圍分組的值的計數

我需要選擇按範圍分組的值的計數。

爲了舉例說明,假設我有一個表columm以下值:1,2,4,5,6,8,9,11,13,16

然後,我想retreave他們的數量在5範圍內,像這樣:

From 0 to 4 there is 3 values (1,2,4) 
From 5 to 9 there is 4 values (5,6,8,9) 
From 10 to 14 there is 2 values (11,13) 
From 15 to 19 there is 1 values (16) 

而且等等......

我該如何在查詢中做到這一點?

回答

13

也許這是你想要什麼:

SELECT 
    5 * (n div 5) as 'from', 
    5 * (n div 5) + 4 as 'to', 
    COUNT(*) 
FROM yourtable 
GROUP BY n div 5; 

爲您的樣品此查詢給你

+------+------+----------+ 
| from | to | count(*) | 
+------+------+----------+ 
| 0 | 4 |  3 | 
| 5 | 9 |  4 | 
| 10 | 14 |  2 | 
| 15 | 19 |  1 | 
+------+------+----------+ 
4 rows in set (0.00 sec) 
+0

這基本上是Guffa在8分鐘後發佈的想法。 – Andomar 2011-02-27 22:29:37

+2

@Andomar不,它不是。 MySQL(n/5)返回一個小數,即使n不是小數。需要'div' – RichardTheKiwi 2011-02-27 23:27:11

+0

工作應該如此! – NemoStein 2011-03-01 13:07:33

3

一種方法是總和+情況下的做法:

select sum(case when col1 between 0 and 4 then 1 end) 
,  sum(case when col1 between 5 and 9 then 1 end) 
,  sum(case when col1 between 10 and 14 then 1 end) 
... 
from YourTable 

另一種方法是有一個範圍表,填寫,如:

start end 
0  4 
5  9 
10  14 

然後,您可以:

select r.start 
,  r.end 
,  count(case when yt.col1 between r.start and r.end then 1 end) 
from YourTable yt 
cross join 
     RangeTable r 
group by 
     r.start 
,  r.end 
2

計算一個可以分組的值。在這種情況下,你只需要5分的價值得到這一結果:

select value/5 as Group, count(*) as Cnt 
from TheTable 
group by value/5 

這會給你的結果是這樣的:

Group Cnt 
0  3 
1  4 
2  2 
3  1 
0
select 
val/5 as grp, 
case val/5 
when 0 then ' 0 to 5' 
when 1 then ' 5 to 10' 
when 2 then '10 to 15' 
when 3 then '15 to 20' 
end 
as grpname, 
count(distinct val) as cnt 
from 
(
select 1 as val 
union select 2 
union select 4 
union select 5 
union select 6 
union select 8 
union select 9 
union select 11 
union select 13 
union select 16 
) a 
group by 
val/5 
0

如何

for(i=MIN_OF_TABLE-1;i<=MAX_OF_TABLE;$i+=RANGE){ 
    SELECT COUNT(`VALUE`),GROUP_CONCAT(`VALUE`) FROM `TABLE` WHERE `VALUE`>i AND `VALUE`<=i+RANGE; 
} 

這將讀取包含您在行中顯示的信息的行=)

+0

我是新來的SQL數據。有沒有一個原因,這不是最好的解決方案? – nyxee 2015-10-22 07:32:28