I think you can get what you want just using with rollup
. The problem is that the sum will appear after the base rows:
select cp.category_name as parent_name, c.category_name, count(*) as numcategories
from products p join
categories c
on p.categoryid = c.id join
categories cp
on c.parentid = cp.id
group by cp.category_name, c.category_name with rollup
To get it before, try this:
select parent_name, category_name, numcategories
from (select cp.category_name as parent_name, c.category_name, count(*) as numcategories
from products p join
categories c
on p.categoryid = c.id join
categories cp
on c.parentid = cp.id
group by cp.category_name, c.category_name with rollup
) t
where category_name is not null
order by category_name,
category_name is null desc;