I have two tables, items & categories, sample data below:
Items:
Title category_id
Item A 1
Item B 2
Item C 3
Item D 2
Item E 3
Item F 2
Categories
category_id category
1 wood
2 plastic
3 metal
What I need to do is to count the total number of items, then list how many are in each category and what % that is of the total
I know I can count each item and total e.g.
select
count(*) as total,
sum(category_id=1) as cat_1,
sum(category_id=2
.... etc etc
But is there a way to do it all without counting each (there maybe new categories added and would like this to stay working) and then joining with categories table to produce the name?
Ideally this is what I’d like to return:
Category how many % of total
wood 1 17%
plastic 3 50%
metal 2 33%
Total 6 100%
(17% is 1/6th => 16.666666667% rounded).
Note, this will also correctly handle empty categories.
SQL Fiddle Example
Output: