I've the following t-sql:
select d.OutageType + '/' + e.Facility Outage,
c.MaterialScopeCode,
count(a.ItemNo) CountofItemNo
into #tt
from _OutageMaterial a
inner join _OutageSchedule b on a.OutageScheduleID = b.OutageScheduleID
inner join _MaterialScope c on a.MaterialScopeID = c.MaterialScopeID
inner join _OutageType d on b.OutageTypeID = d.OutageTypeID
inner join _Facility e on b.FacilityID = e.FacilityID
where ReqQty <> 0
group by c.MaterialScopeCode, e.Facility, d.OutageType
order by d.outagetype, e.Facility, c.MaterialScopeCode
-- /// RESULT /// --
DECLARE @DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE @ColumnName AS NVARCHAR(MAX)
--Get distinct values of the PIVOT Column
SELECT @ColumnName= ISNULL(@ColumnName + ',','') + QUOTENAME(Outage)
FROM (
SELECT DISTINCT Outage
FROM #tt
) AS Scope
--Prepare the PIVOT query using the dynamic
SET @DynamicPivotQuery =
N'SELECT MaterialScopeCode as Scope, ' + @ColumnName + '
FROM #tt
PIVOT(SUM(CountofItemNo)
FOR Outage IN (' + @ColumnName + ')) AS PVTTable'
--Execute the Dynamic Pivot Query
EXEC sp_executesql @DynamicPivotQuery
I've tried many times, but still .. Error. I could not select the temp table because it doesn't created. Invalid Object. I want to put the result of dynamic pivot into temp table.
How can i do that? Please advise.
Thank you.