Das erledigt die Aufgabe für eine Verschachtelungsebene.
Nur Root-Kategorien auflisten, Zählung inklusive Unterkategorien
WITH root AS (
SELECT id AS cat_id, id AS sub_id
FROM category
WHERE is_base_template = false
AND "userId" = 1
)
SELECT c.cat_id, count(*)::int AS entries_in_cat
FROM (
TABLE root
UNION ALL
SELECT r.cat_id, c.id
FROM root r
JOIN category c ON c."parentCategoryId" = r.cat_id
) c
JOIN category_entries_entry e ON e."categoryId" = c.sub_id
GROUP BY c.cat_id;
Der Punkt ist: auf sub_id joinen, aber nach cat_id gruppieren.
Root-Kategorien wie oben, Unterkategorien zusätzlich
WITH root AS (
SELECT id AS cat_id, id AS sub_id
FROM category
WHERE is_base_template = false
AND "userId" = 1
),
ct AS (
SELECT c.cat_id, c.sub_id, count(*)::int AS ct
FROM (
TABLE root
UNION ALL
SELECT r.cat_id, c.id AS sub_id
FROM root r
JOIN category c ON c."parentCategoryId" = r.cat_id
) c
JOIN category_entries_entry e ON e."categoryId" = c.sub_id
GROUP BY c.cat_id, c.sub_id
)
SELECT cat_id, sum(ct)::int AS entries_in_cat
FROM ct
GROUP BY 1
UNION ALL
SELECT sub_id, ct FROM ct WHERE cat_id <> sub_id;
Demo bei db<>fiddle
Beliebige Verschachtelungstiefen
Dafür verwenden Sie einen rekursiven CTE. Beispiel: How to link rows in a many-to-many relationship where types have parents, grandparents etc.
Zur optionalen Kurzschreibweise TABLE parent: siehe Is there a shortcut for SELECT * FROM?.