Table:
CREATE TABLE companies (name VARCHAR(100) NOT NULL, number_of_employees INT NOT NULL, yearly_revenue DECIMAL(30, 2) NOT NULL);
INSERT INTO companies(name, number_of_employees, yearly_revenue) VALUES ('A', 5, 100), ('B', 5, 150), ('C', 15, 200), ('D', 25, 500), ('E', 25, 800);
If I want to count the companies, grouped by the number of employees, then I could write this query:
SELECT
COUNT(*) AS count,
CASE
WHEN number_of_employees BETWEEN 0 AND 10 THEN '0-10'
WHEN number_of_employees BETWEEN 10 AND 20 THEN '10-20'
WHEN number_of_employees > 20 THEN '20-INF'
END AS number_of_employees
FROM companies
GROUP BY
CASE
WHEN number_of_employees BETWEEN 0 AND 10 THEN '0-10'
WHEN number_of_employees BETWEEN 10 AND 20 THEN '10-20'
WHEN number_of_employees > 20 THEN '20-INF'
END
It would output:
count number_of_employees
------------------------------
2 0-10
1 10-20
2 20-INF
Now my goal is to count the number of companies when grouping ranges overlap. Example query to illustrate my goal:
SELECT
COUNT(*) AS count,
CASE
WHEN number_of_employees > 0 THEN '> 0'
WHEN number_of_employees > 10 THEN '> 10'
WHEN number_of_employees > 20 THEN '> 20'
END AS number_of_employees
FROM companies
GROUP BY
CASE
WHEN number_of_employees > 0 THEN '> 0'
WHEN number_of_employees > 10 THEN '> 10'
WHEN number_of_employees > 20 THEN '> 20'
END
It would output:
count number_of_employees
------------------------------
5 > 0
But my desired result looks like this:
count number_of_employees
------------------------------
5 > 0
3 > 10
2 > 20
How should I achieve this?
Bonus question: apart from COUNT(*), I'd also like to know the answer for other aggregation functions, in particular AVERAGE.