简体   繁体   中英

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.

在此处输入图片说明

So if this was pivoted we would get:

在此处输入图片说明

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

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM