2013-06-12 11 views
7

Ho bisogno di contare i record all'interno di intervalli di valori.MySQL - Raggruppa per intervallo

Ad esempio: per il set 1, 7, 9, 23, 33, 35, 1017

select count(myvalue) group by round(myvalue/10) dà qualcosa di simile:

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

Questo funziona bene. Tuttavia, ho bisogno di impostare un limite superiore, in modo che MySQL restituisca 40+ --> 1? Come può essere raggiunto?

risposta

12

è possibile sommare i valori sul lato client o utilizzare due query, possibilmente con union, per andare a prendere i dati, ad esempio:

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 

E 'assolutamente possibile scrivere in un unico query con sottoquery o condizioni complesse ma semplicemente non sarebbe così semplice e manutenibile.

+0

Ho solo sperato che fosse un modo per definire un limite superiore e inferiore (ad es. 20-/40+) per eseguire la query in modo generico. – 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

Non ha funzionato qualche idea? SELEZIONA t.salary come gamma, COUNT (*) come num_employee DA (SELECT stipendio, CASO QUANDO stipendio <= 50000 THEN 'basso' QUANDO stipendio> 50000 e stipendio <= 70000 THEN 'Medium' ELSE 'più alto' END AS RANGE FROM employee_salary) t GROUP BY t.salary – atjoshi

2

vorrei suggerire questa soluzione che prende in prestito da entrambi pilsetnieks e soluzioni di Jayram:

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

Almeno in MySQL, 'range' è una parola riservata: [9.3 Reserved Words] (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

sarebbe utile per l'OP se puoi modificare la tua risposta e inserirla nel contesto di MySQL. – minocha

Problemi correlati