May 13, 2010 at 3:08 pm
How can I sum 2 pivot columns?
this is my sample. you can copy and past it on SQL.
I need to sum the columns and have a 3rd column with the total.
anyone??
CREATE TABLE Test
(
idINT
,idNamevarchar(32)
, ZONEVARCHAR(32)
, SCount int
)
INSERT test VALUES (1, 'Row 1', 'Zone1', 10)
INSERT test VALUES (1, 'Row 1', 'Zone2', 5)
INSERT test VALUES (2, 'Row 2', 'Zone1', 10)
INSERT test VALUES (2, 'Row 2', 'Zone2', 5)
INSERT test VALUES (3, 'Row 3', 'Zone1', 10)
INSERT test VALUES (3, 'Row 3', 'Zone2', 5)
SELECT * FROM Test
DECLARE @Columns VARCHAR(8000)
,@Columns2 VARCHAR(8000)
,@Sql VARCHAR(4000)
SET @Columns = substring((select distinct ',['+Zone+']' from Test group by Zone for xml path('')),2,8000)
SET @Columns2 = substring((select distinct ',IsNull(['+Zone+'],0) as ['+Zone+']' from Test group by Zone for xml path('')),2,8000)
SET @SQL = 'SELECT idName, '+@Columns2+'
FROM
(Select Id, IdName
, Zone, SCount from Test) SourceData
PIVOT
(sum(SCount) for Zone in ('+@Columns+')) pivottable
Order by Id '
exec(@sql)
May 13, 2010 at 3:47 pm
Would the following help?
I'm using OVER (PARTITION BY) to get the total per idName.
Side note: Since you already using dynamic SQL you might want to have a look at the DynamicCrossTab article referenced in my signature. It might perform better than PIVOT....;-)
SET @SQL = 'SELECT idName, '+@Columns2+', total
FROM
(Select Id, IdName,SUM(Scount) OVER (PARTITION BY idName) as total
, Zone, SCount from Test) SourceData
PIVOT
(sum(SCount) for Zone in ('+@Columns+')) pivottable
Order by Id '
May 14, 2010 at 8:55 am
Thank you Lutz
It works !
I will take at look at your article.
thank you again
May 14, 2010 at 9:19 am
MTY-1082557 (5/14/2010)
Thank you LutzIt works !
I will take at look at your article.
thank you again
My pleasure 😀
As a side note: the article I referenced in my signature is not mine. It's all Jeffs fault!! :hehe:
May 14, 2010 at 1:15 pm
🙂
--Jeff Moden
Change is inevitable... Change for the better is not.
Viewing 5 posts - 1 through 5 (of 5 total)
You must be logged in to reply to this topic. Login to reply