Distribution Reports with CASE Buckets in SQL
To see how values spread out, bucket them with CASE and group on the bucket. That gives you a distribution in a few lines.
Individual prices are hard to read in bulk. A distributiongroups them into bands, such as under $10, between $10 and $20, and so on, and counts how many fall in each. The trick: GROUP BY a CASE expression instead of a raw column.
The CASE turns each row's price into a band label; grouping on that label collapses the rows into one per band. To sort the bands in a sensible order, order by min(price) rather than the label text (which would sort alphabetically).
select case
when age < 18 then 'Minor'
when age < 65 then 'Adult'
else 'Senior'
end as age_group,
count(*) as people
from users
group by age_groupKeep the bands non-overlapping and complete, so every row lands in exactly one bucket. A trailing else catches everything above your last threshold.
Schema · Garden ShopTable · products9 columns · 24 rows
One row per product, with price, cost, and inventory levels.
Bucket products into three price bands: 'Under $10','$10 to $19.99', and '$20 and up', and count how many fall in each. Return price_band andproducts, ordered from the cheapest band to the most expensive.
- Columns: price_band, products.
- Rows: one per band (3 rows).
- The products counts across all bands add up to 24 (every product).
Related
Split a group into side-by-side columns with FILTER.
Add subtotal and total rows to a grouped report.
Roll a group's values into one comma-separated cell.
Return several subtotal levels in one grouped query.