Skip to content
Advertisement

How to write a query to produce counts for arbitrary value bands?

My table had 3 fields: id and unit. I want to count how many ids have <10, 10-49, 50-100 etc units. The final result should look like:

Category | countIds  
<10      | 1516  
10 - 49  | 710  
50 - 99  | 632  
etc.

This is the query that returns each id and how many units it has:

select id, count(unit) as numUnits
from myTable
group by id

How can I build on that query to give me the category, countIds result?

Advertisement

Answer

create temporary table ranges (
  seq         int primary key,
  range_label varchar(10),
  lower       int,
  upper       int
);

insert into ranges values
(1, '<10',     0, 9), 
(2, '10 - 49', 10, 49),  
(3, '50 - 99', 50, 99)
etc.

select r.range_label, count(c.numUnits) as countIds
from ranges as r 
join (
  select id, count(unit) as numUnits
  from myTable
  group by id) as c
on c.numUnits between r.lower and r.upper
group by r.range_label
order by r.seq;

edit: changed sum() to count() above.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement