Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL: query help

Tags:

sql

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?

like image 861
dmr Avatar asked Dec 23 '22 00:12

dmr


1 Answers

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.

like image 129
Bill Karwin Avatar answered Jan 10 '23 03:01

Bill Karwin