Skip to content

Instantly share code, notes, and snippets.

@alancoleman
Last active December 21, 2015 22:58
Show Gist options
  • Save alancoleman/6378713 to your computer and use it in GitHub Desktop.
Save alancoleman/6378713 to your computer and use it in GitHub Desktop.
Using CASE and GROUP to count and separate records into groups. This example uses income.
SELECT
(CASE
WHEN i.income < 5000 THEN '- £5000'
WHEN i.income BETWEEN 5000 AND 20000 THEN '£5,000 - £20,000'
WHEN i.income BETWEEN 20000 AND 30000 THEN '£20,000 - £30,000'
WHEN i.income BETWEEN 30000 AND 50000 THEN '£30,000 - £50,000'
WHEN i.income > 50000 THEN '+ £5000'
ELSE 'other'
END) AS income,
COUNT(*) AS users
FROM income_table AS i
WHERE i.income IS NOT NULL
GROUP BY income
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment