I am trying to add subtotal by group and total to a table. I\'ve recreated the data using the following sample.
DECLARE @Sales TABLE(
CustomerName VA
You can use the following query:
SELECT CustomerName, LegalID, Employee, DocDate, DocTotal, DueTotal
FROM (
SELECT CustomerName AS cName, CustomerName,
LegalID, Employee, DocDate, DocTotal, DueTotal,
1 AS ord
FROM Sales
UNION ALL
SELECT CustomerName AS cName, CONCAT('Total ', CustomerName),
NULL, NULL, NULL,
SUM(DocTotal), SUM(DueTotal), 2 AS ord
FROM Sales
GROUP BY CustomerName
UNION ALL
SELECT 'ZZZZ' AS cName, 'Total', NULL, NULL, NULL,
SUM(DocTotal), SUM(DueTotal), 3 AS ord
FROM Sales ) AS t
ORDER BY cName, ord
Demo here
I think this is what you want:
select (case when GROUPING(CustomerName) = 0 and
GROUPING(Employee) = 1 and
GROUPING(DocDate) = 1 and
GROUPING(LegalID) = 1
then 'Total ' + CustomerName
when GROUPING(CustomerName) = 1 and
GROUPING(Employee) = 1 and
GROUPING(DocDate) =1 and
GROUPING(LegalID) = 1 then 'Total'
else CustomerName
end) as CustomerName,
LegalID, Employee,DocDate,
sum(DocTotal) as DocTotal,
sum(DueTotal) as DueTotal
From @Sales
group by grouping sets((LegalID, CustomerName ,Employee, DocDate),
(CustomerName),
()
);