2013-06-12 97 views
7

我需要對值範圍內的記錄進行計數。MySQL - 按範圍分組

例如:設定1, 7, 9, 23, 33, 35, 1017

select count(myvalue) group by round(myvalue/10)給出了類似:

0-10 -> 3 
10-20 -> 0 
20-30 -> 1 
30-40 -> 2 
1010-1020 -> 1 

這工作得很好。但是,我需要設置一個上限,以便MySQL返回40+ --> 1? 這是如何實現的?

回答

12

您可以總結在客戶端中的值或使用兩個查詢,可能與union,獲取數據,如:

select round(myvalue/10), count(myvalue) from table where myvalue < 40 group by round(myvalue/10) 
union 
select '40+', count(myvalue) from table where myvalue >= 40 

這是絕對有可能寫在一個單一的使用子查詢或複雜的條件查詢,但它不會那麼簡單和可維護。

+0

我只是希望這是一種定義上下限(例如20-/40+)以通用方式進行查詢的方法。 – thelost

3
select t.myvalue as [range], count(*) as [occurences] 
from (
    select myvalue, 
    case when myvalue >= 0 and myvalue< 10 then '0-9' 
    when myvalue >= 10 and myvalue< 20 then '10-19' 
    when myvalue >= 20 and myvalue< 20 then '20-29' 
    when myvalue >= 30 and myvalue< 40 then '30-39' 
    else '40+' end as range 
from t) t 
group by t.myvalue 
+0

它沒有工作的任何想法? SELECT t.salary作爲範圍,COUNT(*)作爲num_employee FROM (SELECT工資, CASE WHEN薪金<= 50000 THEN '最低' WHEN薪水> 50000和薪水<= 70000 THEN '中' ELSE '最高' END AS RANGE FROM employee_salary)t GROUP BY t.salary – atjoshi

2

我建議這個解決方案,對pilsetnieks和Jayram的解決方案借鑑:

SELECT 
    COUNT(*) AS cnt, 
    IF (myvalue >= 40; -1; ROUND(myvalue/10) AS range 
FROM t 
GROUP BY range 
+0

至少在MySQL中,'range'是一個保留字:[9.3保留字](http://dev.mysql.com/doc/refman/5.5/en/reserved-words.html) – berliner

0
SELECT case 
    when myvalue >= 0 and myvalue< 10 then '0-9' 
    when myvalue >= 10 and myvalue< 20 then '10-19' 
    when myvalue >= 20 and myvalue< 20 then '20-29' 
    when myvalue >= 30 and myvalue< 40 then '30-39' 
    else '40+' 
    end as range 
from t 
group by range 
+1

這對於OP如果你可以編輯你的答案並把它放到MySQL的上下文中。 – minocha