Search code examples
sqlsql-serverpivotdynamic-pivot

SQL - Pivoting on Column and Row Values


I'm trying to Pivot a Table on X and Y position. The table is in a format similar to below.

Each row has a value which is relative to its Row and Column Position.'AThing' and 'FileName' are to be ignored in the data set.

enter image description here

So if this was pivoted we would get:

enter image description here

Iv'e been trying for a while but can't seem to figure it out, any ideas?

EDIT: Number of Fields are dynamic per 'FileName'. I have managed to extract the column names but not the data using:

-- Construct List of Columns to Pivot
SELECT @PivotCols = 
STUFF(
    (SELECT ',' + QUOTENAME(FieldName) 
     FROM #Data
     GROUP BY ColPos, FieldName
     ORDER BY ColPos ASC
     FOR XML PATH(''),TYPE).value('.', 'NVARCHAR(MAX)') 
,1,1,'')

SET @PivotQuery =
SELECT ' + @PivotCols + N' 
FROM 
(
    SELECT ColPos, FieldName
    FROM #Data
    GROUP BY ColPos, FieldName
) x
PIVOT 
(
    MIN(ColPos)
    FOR FieldName IN (' + @PivotCols + N')
) p' 

EXEC sp_executesql @PivotQuery

Solution

  • Please try this code:

     DECLARE @columns NVARCHAR(MAX), @sql NVARCHAR(MAX);
    SET @columns = N'';
    SELECT @columns += N', p.' + QUOTENAME(FieldName)
      FROM (SELECT distinct p.FieldName FROM Tablename AS p
      ) AS x;
    SET @sql = N'
    SELECT ' + STUFF(@columns, 1, 2, '') + '
    FROM
    (
      SELECT p.Value, p.FieldName, p.RowPos
       FROM Tablename AS p
    ) AS j
    PIVOT
    (
      MAX(Value) FOR FieldName IN ('
      + STUFF(REPLACE(@columns, ', p.[', ',['), 1, 1, '')
      + ')
    ) AS p;';
    PRINT @sql;
    EXEC sp_executesql @sql;