I am trying to manipulate R12 sales info so that I have a summary of qty shipped to each ship to ID. I need these distinct ship to's in columns in a report. Is there a way to use the column headers from the pivot table? If I first create ##TempTableTesting, I don't know how to rename the columns with the ship to IDs. But if I don't first create the table, it says invalid object later on. What is the best way around this?
IF OBJECT_ID('tempdb..#R12') IS NOT NULL
DROP TABLE #R12
SELECT #t.inv_mast_uid,
#t.ship_to_id,
SUM(#t.qty_shipped) as qty_shipped
INTO #R12
FROM #t
WHERE #t.invoice_date BETWEEN DATEADD(MONTH, DATEDIFF(MONTH, 0,DATEADD(MONTH, DATEDIFF(MONTH, -1, GETDATE())-1, 0))-12, 0) AND DATEADD(MONTH, DATEDIFF(MONTH, -1, GETDATE())-1, -1)
GROUP BY #t.inv_mast_uid,
#t.ship_to_id
IF OBJECT_ID('TEMPDB.dbo.##TempTableTesting') IS NOT NULL
DROP TABLE ##TempTableTesting
DECLARE @Columns NVARCHAR(MAX)
SELECT @Columns = COALESCE(@Columns + ',','') + QUOTENAME(ship_to_id) FROM (SELECT DISTINCT #R12.ship_to_id FROM #R12) shiptos
DECLARE @sql NVARCHAR(MAX)
SET @sql = 'SELECT inv_mast_uid, ' + @Columns + '
into ##TempTableTesting
FROM #R12
PIVOT(SUM(qty_shipped)
FOR ship_to_id IN (' + @Columns + ')) AS PVTTable'
execute sp_executesql @sql