Vistas por subcategoría
Un análisis más detallado de las vistas por tema, pero sin sumarlas. Las entradas con la subcategoría “(none)” corresponden a temas ubicados directamente en las categorías de primer nivel.
SELECT
topcat AS "Categoría",
subcat AS "Subcategoría",
SUM(views) AS "Vistas de subcategoría"
FROM (
/* Vistas de temas en subcategorías de nivel inferior. */
SELECT
topcat.name AS topcat, subcat.name AS subcat, SUM(topics.views) AS views
FROM topics
INNER JOIN categories subcat ON topics.category_id = subcat.id
INNER JOIN categories topcat ON subcat.parent_category_id = topcat.id
GROUP BY topcat.name, subcat.name
UNION
/* Vistas de temas en categorías de primer nivel (excluyendo subcategorías de nivel inferior). */
SELECT
topcat.name AS topcat, '(none)', SUM(topics.views) AS views
FROM topics
INNER JOIN categories topcat ON topics.category_id = topcat.id
WHERE topcat.parent_category_id IS NULL
GROUP BY topcat.name
) AS views_by_cat
GROUP BY topcat, subcat
/* Ordena la salida por categoría o por vistas. Habilita una de estas opciones: */
/* ORDER BY topcat, subcat */
ORDER BY "Vistas de subcategoría" DESC