Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grouping by intervals

Tags:

sql

mysql

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.

like image 353
Dave Sherohman Avatar asked Oct 13 '08 11:10

Dave Sherohman


People also ask

How does a grouping by works?

The GROUP BY statement groups rows that have the same values into summary rows, like "find the number of customers in each country". The GROUP BY statement is often used with aggregate functions ( COUNT() , MAX() , MIN() , SUM() , AVG() ) to group the result-set by one or more columns.

What are grouping sets?

GROUPING SETS are groups, or sets, of columns by which rows can be grouped together. Instead of writing multiple queries and combining the results with a UNION, you can simply use GROUPING SETS. GROUPING SETS in SQL can be considered an extension of the GROUP BY clause.

What are group intervals?

1. n. [Geophysics] The distance between geophones or groups of geophones. Synonyms: geophone interval. See: geophone, group, source, spacing.

How do you group data in intervals?

(i) Use a dot plot to represent the data. (ii) On your dot plot, circle the dots that are in each interval of the frequency table below. Then complete the frequency table. (iii) Analyze the data.


2 Answers

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;
like image 153
Jouni K. Seppänen Avatar answered Oct 02 '22 08:10

Jouni K. Seppänen


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         
like image 32
ila Avatar answered Oct 02 '22 09:10

ila