Here is an example using the Microsoft Northwind database. I created a simple pivot on the
Orders
table as follows
SELECT CustomerID, ROW_NUMBER() OVER (ORDER BY CustomerID) as rn,
ISNULL([1996],0) as [1996],
ISNULL([1997],0) as [1997],
ISNULL([1998],0) as [1998]
INTO #temp
FROM
(
SELECT CustomerID, YEAR(OrderDate) as Y, Freight
FROM ORDERS
WHERE CustomerID IN ('ALFKI','BLAUS','DRACD')
) source
PIVOT
(
SUM(Freight) FOR Y IN ([1996],[1997],[1998])
) pvt
Points to note - I've inserted the PIVOT results into a temporary table (you can just as easily use a Table variable).
I've also included a row number.
The results of that are:
ALFKI 1 0.00 114.42 111.16
BLAUS 2 0.00 38.64 129.62
DRACD 3 35.99 33.35 236.70
I can then union that with a total, using the row number to make sure the Total ends up at the bottom.
select CustomerID, [1996],[1997],[1998] from
(
select rn, CustomerID, [1996],[1997],[1998] FROM #temp
UNION
select MAX(rn) + 1, 'TOTAL', SUM([1996]),SUM([1997]),SUM([1998])
from #temp
) source
ORDER BY rn
I use a sub-query here because I don't want the row number to be part of the final query, but it's not essential if you just ignore the row number in your presentation layer.
Results after the final UNION :
ALFKI 0.00 114.42 111.16
BLAUS 0.00 38.64 129.62
DRACD 35.99 33.35 236.70
TOTAL 35.99 186.41 477.48