Input Data:
| Occupation | Name |
|---|---|
| Doctor | Smith |
| Doctor | George |
| Professor | Baker |
| Singer | Davis |
| Singer | Head |
| Actor | Miller |
Query:
SELECT [Doctor], [Professor], [Singer], [Actor]
FROM (
SELECT Occupation, Name,
ROW_NUMBER() OVER (PARTITION BY Occupation ORDER BY Name) AS rn
FROM OCCUPATIONS
) AS SourceTable
PIVOT
(
MAX(Name) FOR Occupation IN ([Doctor], [Professor], [Singer], [Actor])
) AS PivotTable
ORDER BY rn;
Result
| Doctor | Professor | Singer | Actor |
|---|---|---|---|
| George | Baker | Davis | Miller |
| Smith | NULL | Head | NULL |
My question is if an aggregate function is being used like max, how am I getting multiple values for occupations?
I tried removing row number and searching if row number was playing any part in this And I am still not sure
With the
ROW_NUMBERyou can define the order of the result set.Of course you could achieve this, by changing he order in the row_number window function
fiddle