Skip to content

Instantly share code, notes, and snippets.

@latompa
Created October 23, 2009 21:27
Show Gist options
  • Save latompa/217199 to your computer and use it in GitHub Desktop.
Save latompa/217199 to your computer and use it in GitHub Desktop.
count in buckets
-- table
create table members (id integer, age integer);
-- data
insert into members (id,age) values
(1,10), (2,20), (3,30), (4,25), (5,28), (6,37), (7,38), (8,68), (9,9);
-- query
select
SUM(case when age between 1 and 20 then 1 else 0 end) as "1-20",
SUM(case when age between 21 and 30 then 1 else 0 end) as "21-30",
SUM(case when age between 31 and 40 then 1 else 0 end) as "31-40",
SUM(case when age between 41 and 50 then 1 else 0 end) as "41-50",
SUM(case when age > 51 then 1 else 0 end) as "> 51"
from members
-- results
1-20 21-30 31-40 41-50 > 51
3 3 2 0 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment