Hi Everyone,
I was trying to create a Common Table Express to store some data that I need a bunch of inner join. Then I would like to pivot the result using dynamic pivot columns. I wrote the below query but I'm getting the error " Common table expression defined but not used." How can I create a pivot query base on a CTE? BTW...I can do it without the CTE but I would like to know if I can do it with CTE.
DECLARE @cols nvarchar(max) DECLARE @sql nvarchar(max) SELECT @cols = isnull(@cols + ', ', '') + '[' + Convert(varchar(max),T.CostCenterNumber) + ']' FROM (SELECT distinct CostCenterNumber FROM CostCenters) as T ;With PivotData as ( SELECT B.[Year], C.CostCenterNumber, C.CostCenterName, E.[Description] as GLClass, D.Code, D.[GLDescription], A.Total From GeneralLedgers A inner join Years B on A.YearID = B.ID inner join CostCenters C on A.CostCenterID = C.ID inner join GLCodes D on A.GLCodeID = D.ID inner join GLClassificationTypes E on D.GLClassificationTypeID = E.ID) SELECT @sql = ' Select * From( SELECT [Year], CostCenterNumber, GLClass, Code, GLDescription, Total FROM PivotData) as T PIVOT ( Max(Total) for [CostCenterNumber] in (' + @cols + ') )) as P' EXEC(@sql)
- Edited by zXSwordXz 8 hours 0 minutes ago