Comment utiliser le pivot dans le server sql (sans agrégats)?

aidez-moi s'il vous plaît à résoudre ce problème: On vous donne un tableau, contenant deux colonnes: colonne est l'un des suivants:

Doctor Professor Singer Actor 

Ecrire une requête pour afficher les noms sous l'occ. dans le format suivant:

 +--------+-----------+--------+------+ | Doctor | Professor | Singer | Actor| +--------+-----------+--------+------+ 

Les noms doivent être listés par ordre alphabétique.

Exemple d'input

 Name Occupation Meera Singer Ashely Professor Ketty Professor Christeen Professor Jane Actor Jenny Doctor Priya Singer 

Sortie d'échantillon

 Jenny Ashley Meera Jane Samantha Christeen Priya Julia NULL Ketty NULL Maria 

Remarque

Imprimer "NULL" quand il n'y a plus de noms correspondant à une occupation.

J'ai essayé d'utiliser:

 SELECT * FROM ( SELECT [Name], [Occupation] FROM occupations ) AS source PIVOT ( max([Name]) FOR [occupation] IN ([Doctor], [Professor], [Singer], [Actor]) ) as pvt; 

ce qui donne la sortie suivante:

 Priya Priyanka Kristeen Samantha 

Comment le réparer ?

Vous avez juste besoin de donner à chaque nom un numéro de rangée en fonction de son occupation et de l'ordre alphabétique .. puis d'inclure ce numéro de ligne dans votre requête pivot.

 CREATE TABLE Occupations ( NAME VARCHAR(MAX), Occupation VARCHAR(MAX) ) INSERT INTO Occupations VALUES ('Samantha','Doctor'), ('Julia','Actor'), ('Maria','Actor'), ('Meera','Singer'), ('Ashley','Professor'), ('Ketty','Professor'), ('Christeen','Professor'), ('Jane','Actor'), ('Jenny','Doctor'), ('Priya','Singer'); SELECT [Doctor], [Professor], [Singer], [Actor] FROM (SELECT ROW_NUMBER() OVER (PARTITION BY Occupation ORDER BY Name) rn, [Name], [Occupation] FROM Occupations ) AS source PIVOT ( MAX([Name]) FOR [occupation] IN ([Doctor],[Professor],[Singer],[Actor]) ) as pvt ORDER BY rn DROP TABLE Occupations