HiveBrain v1.2.0
Get Started
← Back to all entries
snippetsqlModerate

How do I calculate COUNT(*) for a range without needing to use multiple queries in mysql

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
withoutneedingqueriesrangemysqlforcalculatehowmultiplecount

Problem

I am using MySQL and I need help using COUNT(*) for a range of values within a table.

I have a table named PERSON (In the live system I expect several hundred thousand records or more).

Name    Result
a       100
b       130.45
c       182.96
d       65.45
e       199
f       245


I need to query the table to find out how many records belong to a given range. For example, how many persons belong to 0-50 range. Range values are dynamic. So the expected result is something like:

Range       Count
0-50            0
51-100          2
101-150         1
151-200         2
201-250         1


Off course I can do:

SELECT COUNT(*) FROM PERSON WHERE RESULT  50 AND RESULT <= 100


and so on for all ranges...

However, there must be a better, more efficient way to do this?

Solution

using the case you can define any range you want.

select 
  case 
    when RESULT between 0 and 50 then '0-50'
    when RESULT between 50 and 100 then '51-100'
    when RESULT between 100 and 150 then '101-150'
    when RESULT between 150 and 200 then '151-200'
    when RESULT between 200 and 250 then '201-250'
    else 'OTHERS'
  end as `Range`,
  count(1) as `Count`
from PERSON
group by `Range`;

Code Snippets

select 
  case 
    when RESULT between 0 and 50 then '0-50'
    when RESULT between 50 and 100 then '51-100'
    when RESULT between 100 and 150 then '101-150'
    when RESULT between 150 and 200 then '151-200'
    when RESULT between 200 and 250 then '201-250'
    else 'OTHERS'
  end as `Range`,
  count(1) as `Count`
from PERSON
group by `Range`;

Context

StackExchange Database Administrators Q#22491, answer score: 15

Revisions (0)

No revisions yet.