具有多列的单个总计 ROLLUP

Single grand total ROLLUP with multiple columns

我希望在我的 table 中添加一个工资总计,这也是基于对多个列的选择。我坚持的代码如下:

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);

执行上面的查询以包括总计和按国家/地区总计分组的其他行,但后面的其他列为空。有没有办法重写它以便只有一个总计行?

我提前道歉,因为我对此很陌生。我看过其他问题,这就是我能够拼凑的。谢谢!

您可以使用 grouping sets 控制分组。如果您想要您拥有的组加上国家/地区的总数和总总数,则:

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), () );