Add GROUP Name and Subtotal in SQL

Viewed 40

I have this SQL code and it works fine, but I want to show the department name and total of departments before the group by start.

Please look at the screenshot for more detail:

look Example In Picture

select department, EmpName, Sum(Debi), sum(Credi)
from Total_Income
group by EmpName, Department
1 Answers

You can use group by rollup:

select department, coalesce(EmpName, 'Total'), Sum(Debi), sum(Credi)
from Total_Income
group by rollup (department, EmpName)
having department is not null
order by department, case when EmpName is null then 0 else 1 end, EmpName

(Optional SQL standard feature T431, Extended grouping capabilities.)

Related