This question already has an answer here:
I have a situation like this
+---------+-----------+------------+
| FieldNo | FieldName | Substring |
+---------+-----------+------------+
| 1 | A | 8 |
| 1 | A | A |
| 1 | A | DC |
| 2 | B | 7 |
| 3 | C | 22 |
| 3 | C | 37 |
+---------+-----------+------------+
Need output like this:
+----+------+------+
| A | B | C |
+----+------+------+
| 8 | 7 | 22 |
| A | Null | 37 |
| DC | Null | Null |
+----+------+------+
Any suggestions how I can do this in SQL Server?
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT ',' + QUOTENAME(Field_name)
from bear_crossjoin
group by FIELD_NAME, FIELDNUMBER
order by FIELDNUMBER
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = N'SELECT ' + @cols + N' from
(
select substring, Field_name
from bear_crossjoin
) x
pivot
(
max(substring)
for field_name in (' + @cols + N')
) p '
exec sp_executesql @query
It seems you are trying to PIVOT by row number instead of directly on the field names. The approach below pivots using the row number to get the desired output:
This yields the desired output:
I've assumed the table name as tblTemp. Try this
fiddle