I understand this question has been asked numerous times however I can't seem to find an example that fits, or works, in my situation. I have a query that outputs data in rows however I need it by columns. The pivot column is an item description and the amount of columns can vary. I have the code below which builds the columns, this is working correctly.
DECLARE @Columns as VARCHAR(MAX)
SELECT @Columns = COALESCE(@Columns + ', ','') + QUOTENAME(JOB_GROUP)
FROM
(SELECT DISTINCT ITEM.ITEM_DESCRIPTION
FROM ITEM LEFT JOIN MATRIX_DETAIL ON ITEM.ITEM_ID= MATRIX_DETAIL.ITEM_ID
WHERE MATRIX_DETAIL.MATRIX_ID = 1
) AS B
ORDER BY B.ITEM_DESCRIPTION
The code below is where I'm having issues. I'm not sure if it's the joins or what is going. For the final report it will have quite a few more columns before the pivoted columns start, for this example I'm just trying to get one column to appear correctly and then I can build it out from there. The code below is telling me I've got invalid column names, etc. I'm missing something obvious, and hopefully easy, in this. Any help would be appreciated.
DECLARE @SQL as VARCHAR(MAX)
SET @SQL = 'SELECT ACTION_CODE_KIT, ' + @Columns + '
FROM
(SELECT MATRIX.ACTION_CODE_KIT
FROM MATRIX INNER JOIN
MATRIX_ACTION_CODES ON MATRIX.MATRIX_ID = MATRIX_ACTION_CODES.MATRIX_ID INNER JOIN
MATRIX_DETAIL ON MATRIX_ACTION_CODES.ACTION_CODE_ID = MATRIX_DETAIL.ACTION_CODE_ID LEFT OUTER JOIN
ITEM ON MATRIX_DETAIL.ITEM_ID = ITEM.ITEM_ID LEFT OUTER JOIN
[PLAN] ON MATRIX_ACTION_CODES.PLAN_CODE = [PLAN].PLAN_CODE
) as PivotData
PIVOT
(
MIN(ITEM_ID)
FOR MATRIX.ACTION_CODE_KIT IN(' + @Columns + ')
) AS PivotResult'
EXEC (@sql)