Search code examples
mysqlsubquerysum

Sum of subquery with sum


I've a query which give me a column with totals, the query looks like this:

SELECT SUM( BoekRegelBedrag ) AS total, 
    BoekRegelPeriode, BoekRegelGrootboekNr, 
    BaOmschrijving, BaSoort 
FROM BoekstukRegels 
LEFT JOIN ( 
        SELECT BaOmschrijving, BaSoort, BaGbNumber 
        FROM balansen 
        WHERE BauserId = 45 
        GROUP BY BaGbNumber 
    ) tbl ON BoekRegelGrootboekNr = BaGbNumber 
WHERE BoekregelUserId = 45 
    AND BoekRegelPeriode BETWEEN '201201' AND '201212' 
    AND BaSoort = 2 
GROUP BY BoekRegelGrootboekNr

What I want now is to sum those results of the given query.

How can I do this?


Solution

  • Add the WITH ROLLUP modifier to your existing query. That will return an extra row, with NULL values in your regular columns and the desired grand total value in your total column.

    SELECT SUM( BoekRegelBedrag ) AS total, BoekRegelPeriode, BoekRegelGrootboekNr, BaOmschrijving, BaSoort 
        FROM BoekstukRegels 
            LEFT JOIN (SELECT BaOmschrijving, BaSoort, BaGbNumber 
                           FROM balansen 
                           WHERE BauserId = 45 
                           GROUP BY BaGbNumber )tbl 
                ON BoekRegelGrootboekNr = BaGbNumber 
        WHERE BoekregelUserId = 45 
            AND BoekRegelPeriode BETWEEN '201201' AND '201212' 
            AND BaSoort = 2 
        GROUP BY BoekRegelGrootboekNr
        WITH ROLLUP