How to Group Rows Into Buckets with Count in a SQL Query
How can we group rows returned from a SQL query into buckets with the count in each bucket?
Example grouping with bucket counts
Suppose we have a table of people with
We want to group people into categories and get the number of people in each category.
|Between 20 and 30||2|
SQL query to group rows into buckets with counts
We can use a simple
CASE expression to bucket rows based on certain column values.
SELECT CASE WHEN age >= 0 AND age <= 20 THEN 'Below 20' WHEN age > 20 AND age <= 30 THEN 'Between 20 and 30' WHEN age > 30 THEN 'Above 30' END category, count(*) AS count FROM tableName GROUP BY 1