patternsqlModerate
sql server getting total for each group
Viewed 0 times
totaleachgroupsqlgettingforserver
Problem
Not sure how to go about this:-
I have a query
I can get a sum by doing a grouping
How can I get the total per city as a separate row under each city ?
Expected Sample Result:
I have a query
select name, city, salary from EmployeeI can get a sum by doing a grouping
select name, city, sum(salary) total_salary from Employee group by name, cityHow can I get the total per city as a separate row under each city ?
Expected Sample Result:
Name City Salary
n1 c1 10
n2 c1 20
T1 c1 30
n3 c2 20
n4 c2 50
T2 c2 70Solution
You can use
Example of use from Microsoft Technet: Using
GROUP BY with the GROUPING SETS () modifier:select name, city, sum(salary) total_salary
from Employee
group by grouping sets ((city, name), (city)) ;Example of use from Microsoft Technet: Using
GROUP BY with ROLLUP, CUBE, and GROUPING SETSCode Snippets
select name, city, sum(salary) total_salary
from Employee
group by grouping sets ((city, name), (city)) ;Context
StackExchange Database Administrators Q#198473, answer score: 13
Revisions (0)
No revisions yet.