I am having difficulty in understanding the below SQL query to pivot the table,
Table Name : Occupations
Name | Occupation
-----------------
Sam | Actor
Julia | Singer
Ketty | Actor
Expected result:
Actor | Singer
----------------
Sam | Julia
Ketty | null
I got only one row, When I executed the below query,
Select [Actor],[Singer] From ( Select Occupation,Name From Occupations
)sub Pivot (Max(Name) For Occupation in ([Actor],[Singer])) pvt
output :
Actor | Singer
----------------
Sam | Julia
When I modified the above query using RowNumber(), I got the expected result(multiple rows).
Select [Actor],[Singer]
From ( Select Occupation,Name,Row_Number() over(partition by Occupation order by Name)SNo
From Occupations )sub
Pivot (Max(Name) For Occupation in ([Actor],[Singer])) pvt
Can you explain , How adding Row_Number function in the sub query gives multiple row?
PIVOTandRow_Number()works ?