Search code examples
sqlt-sqlgroupingunionrollup

Single grand total ROLLUP with multiple columns


I am looking to add a single grand total for salaries to my table, which is also based on a selection of multiple columns. The code I'm stuck on is below:

SELECT country, state1, city, street, ID, lastname + ', ' + firstname AS 'Name', SUM(salary) AS 'AnnualSalary'
FROM geography1 JOIN address ON street = streetname JOIN employee ON ID = PID
WHERE termdate IS NULL
GROUP BY country, state1, city, street, gender, lastname, firstname

UNION ALL

SELECT COALESCE(country,'TOTAL'), NULL AS state1, NULL AS city, NULL AS street, NULL AS gender, NULL AS lastname, NULL AS lastname, SUM(salary) AS 'AnnualSalary'
FROM geography1 JOIN address ON street = streetname JOIN employee ON ID = PID
WHERE termdate IS NULL
GROUP BY ROLLUP(country);

The query above executes to include the grand total and additional rows that group by country totals, but the other columns that follow are null. Is there a way to rewrite this so that there is only a single grand total row?

I apologize in advance for being so new to this. I've looked at other questions and this is what I've been able to piece together. Thanks!


Solution

  • You can control the groupings using grouping sets. If you want the groups that you have plus the total for country and the overall total, then:

    SELECT country, state1, city, street, ID, lastname + ', ' + firstname AS Name,
           SUM(salary) AS 'AnnualSalary'
    FROM geography1 JOIN
         address
         ON street = streetname JOIN 
         employee ON ID = PID
    WHERE termdate IS NULL
    GROUP BY GROUPING SETS ( (country, state1, city, street, gender, lastname, firstname), (country), () );