I have table with values, described as:
| Occupation String | Name String |
|---|---|
| Developer | A |
| Developer | B |
| Designer | X |
| Coder | Y |
| Coder | Z |
I need values in pivot format as:
| Designer | Developer | Coder |
|---|---|---|
| X | A | Y |
| Null | B | Z |
Can anyone help on this ?
Thanks in advance
I have table with values, described as:
| Occupation String | Name String |
|---|---|
| Developer | A |
| Developer | B |
| Designer | X |
| Coder | Y |
| Coder | Z |
I need values in pivot format as:
| Designer | Developer | Coder |
|---|---|---|
| X | A | Y |
| Null | B | Z |
Can anyone help on this ?
Thanks in advance
The basic PIVOT with ROW_NUMBER() will do things for you:
SELECT [Developer],
[Designer],
[Coder]
FROM (
SELECT *,
ROW_NUMBER() OVER (PARTITION BY Occupation ORDER BY (SELECT NULL)) RN
FROM #temp
) as t
PIVOT (
MAX(Name) FOR Occupation IN ([Developer],[Designer],[Coder])
) as pvt
Output:
Developer Designer Coder
A X Y
B NULL Z
If the number of Occupations may vary then you need dynamic SQL:
DECLARE @columns nvarchar(max),
@sql nvarchar(max)
SELECT @columns = (
SELECT DISTINCT ','+QUOTENAME(Occupation)
FROM #temp
FOR XML PATH('')
)
SELECT @sql = N'
SELECT '+STUFF(@columns,1,1,'')+'
FROM (
SELECT *,
ROW_NUMBER() OVER (PARTITION BY Occupation ORDER BY (SELECT NULL)) RN
FROM #temp
) as t
PIVOT (
MAX(Name) FOR Occupation IN ('+STUFF(@columns,1,1,'')+')
) as pvt'
EXEC sp_executesql @sql
Note: I have used ORDER BY (SELECT NULL) just to get some random ordering. Better use some actual field for this purpose.
ROW_NUMBER() OVER (PARTITION BY Occupation ORDER BY (SELECT NULL)) will define some order, but this is not predictable. I'd say, that this approach - even if it works! - is something one should not do...(SELECT NULL) OP can use ANY field he need/can. It is just an example. Personally I use such ordering if I don't have any field to do sort with and this is rare thing in our (company) DBs.(SELECT NULL) that gives some random ordering.