This may sound crazy to some of you more seasoned SQL folks than I, but in one particular report that I'm trying to make work, I would like to try to pivot some results into a temp table, and then use the temp table to pull in a couple other columns.
The pivot is dynamically generated. Pivots in SQL are not my favorite thing. It's like I one day just decided I don't like PIVOT in SQL, and sort of set my mind against really learning it.
That said, I have gotten it to work a couple of times.
So, anyway, I've got this dynamic PIVOT working, but I need to add a couple more fields to the dataset, so I can make it work in Reporting Services.
Here's what the dynamic PIVOT sql is doing: (It's not the first time I've dealt with a dynamic pivot, but I did grab someone else's idea online, and just modified for my table/field names, and it works beautifully):
Is there not some way to tell SQL to dump PIVOT values in to a table? If so, can anyone help me key in on that... either for use in the dynamic sql above, or just with any plan PIVOT? Certainly, I can figure out how to make it work in the dynamic piece if I can do it with PIVOT without dynamic SQL.
Thanks in advance for any help
"But thanks be to God, which giveth us the victory through our Lord Jesus Christ." 1 Corinthians 15:57
The pivot is dynamically generated. Pivots in SQL are not my favorite thing. It's like I one day just decided I don't like PIVOT in SQL, and sort of set my mind against really learning it.
That said, I have gotten it to work a couple of times.
So, anyway, I've got this dynamic PIVOT working, but I need to add a couple more fields to the dataset, so I can make it work in Reporting Services.
Here's what the dynamic PIVOT sql is doing: (It's not the first time I've dealt with a dynamic pivot, but I did grab someone else's idea online, and just modified for my table/field names, and it works beautifully):
Code:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX);
SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.Category)
FROM #ForPivot c
FOR XML PATH('), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,')
set @query = 'SELECT ReportMonth, ' + @cols + ' from
(
select ReportMonth
, NumberWidgets
, Category
from #ForPivot
) x
pivot
(
max(NumberWidgets)
for Category in (' + @cols + ')
) p '
execute(@query)
Is there not some way to tell SQL to dump PIVOT values in to a table? If so, can anyone help me key in on that... either for use in the dynamic sql above, or just with any plan PIVOT? Certainly, I can figure out how to make it work in the dynamic piece if I can do it with PIVOT without dynamic SQL.
Thanks in advance for any help
"But thanks be to God, which giveth us the victory through our Lord Jesus Christ." 1 Corinthians 15:57