Vistas por categoría de nivel superior

Vistas por categoría de nivel superior

Incluyendo el total general de todas las vistas de temas en tu foro desde el principio.

/* SELECT exterior para ocultar la columna de ordenación artificial y ordenar por ella. */
SELECT "Category", "Views"
FROM (

    /* Vistas por categoría de nivel superior. */
    SELECT 
        topcat AS "Category", 
        SUM(views) AS "Views",
        0 AS sortorder /* Columna de ordenación artificial, aquí para ordenar al principio. */
    
    FROM (
        /* Vistas de temas en categorías de nivel inferior. */
        SELECT
            topcat.name AS topcat, 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
        
        UNION
    
        /* Vistas de temas en categorías de nivel superior (excluyendo categorías de nivel inferior). */
        SELECT
            topcat.name AS topcat, 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
    
    UNION
    
    /* Agregando una fila TOTAL al final. */
    SELECT 
        'GRAND TOTAL' AS "Category",
        SUM(topics.views) AS "Views",
        1 AS sortorder /* Columna de ordenación artificial, aquí para ordenar al final. */
    FROM
        topics
    GROUP BY "Category"
    
    /* Ordena la salida por categoría o por vistas. Habilita una de estas opciones: */
    /* ORDER BY topcat, subcat */
    ORDER BY "Views" DESC

) AS views_by_cat_with_total

ORDER BY sortorder, "Category"