Link to home
Start Free TrialLog in
Avatar of clintnash
clintnashFlag for United States of America

asked on

SQL Pivot add row totals

With the help of Pawan Kumar (thanks Pawan) this morning I was able to get a working Pivot table, I converted it to a dynamic and everything was flying along smoothly until I tried to add a row total in.  

This is the sample data and working query.
CREATE TABLE #Pivots
(
	 CustID INT 	  
	,Age	INT
	,EventID INT
)
GO

INSERT INTO #Pivots VALUES 
(197305	 ,   18	,   890 ),
(151699	 ,   18	,   890 ),
(199423	 ,   19	,   890 ),
(212585	 ,   19	,   890 ),
(198255	 ,   19	,   891 ),
(201954	 ,   20	,   891 )
GO


DECLARE @DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE @ColumnName AS NVARCHAR(MAX)
 
--Get distinct values of the PIVOT Column 
SELECT @ColumnName= ISNULL(@ColumnName + ',','') 
       + QUOTENAME(Age)
FROM (SELECT DISTINCT age FROM #Pivot) AS age

SET @DynamicPivotQuery = 
  N';WITH CTE AS
  
  (
	SELECT Age, eventID
	FROM #playlist 
		

)
SELECT DISTINCT eventID , ' + @ColumnName + '
    FROM CTE
   PIVOT ( COUNT(Age) FOR Age IN (' + @ColumnName + ')) AS PVTTable'


EXEC sp_executesql @DynamicPivotQuery

Open in new window


It produces the following results
eventID	18	19	20
890	         2	  2	 0
891	         0	  1	 1

Open in new window


and I want to add a row total
eventID	18	19	20     Total
890	         2	  2	 0         4
891	         0	  1	 1         2

Open in new window


Any help that you can provide is, as always, greatly appreciated.
thank you
ASKER CERTIFIED SOLUTION
Avatar of ste5an
ste5an
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of clintnash

ASKER

Brilliant!. Thank you very much for your help today.