tags:

views:

325

answers:

2

Given a table (mytable) containing a numeric field (mynum), how would one go about writing an SQL query which summarizes the table's data based on ranges of values in that field rather than each distinct value?

For the sake of a more concrete example, let's make it intervals of 3 and just "summarize" with a count(*), such that the results tell the number of rows where mynum is 0-2.99, the number of rows where it's 3-5.99, where it's 6-8.99, etc.

+10  A: 

The idea is to compute some function of the field that has constant value within each group you want:

select count(*), round(mynum/3.0) foo from mytable group by foo;
Jouni K. Seppänen
If you changed this slightly to 3*round(mynum/3.0) you'd have the lower limit of each grouping displayed for you.
DBMarcos99
+1  A: 

I do not know if this is applicable to mySql, anyway in SQL Server I think you can "simply" use group by in both the select list AND the group by list.

Something like:

select 
    CASE 
        WHEN id <= 20 THEN 'lessthan20' 
        WHEN id >  20 and id <= 30 THEN '20and30' ELSE 'morethan30' END,
    count(*) 
from Profiles 
where 1=1 
group by 
    CASE 
        WHEN id <= 20 THEN 'lessthan20' 
        WHEN id >  20 and id <= 30 THEN '20and30' ELSE 'morethan30' END

returns something like

 column1     column2    
 ----------  ---------- 
 20and30     3          
 lessthan20  3          
 morethan30  13
ila
I'm not sure whether this would work in MySQL either, but it has the problem of being limited to only the groups you define rather than covering every range of three which occurs (without, e.g., defining 334 cases if your values go up to 1000, then hoping a 1002 never shows up).
Dave Sherohman