How to use pivot in sql server (without aggregates )?
SELECT [Doctor], [Professor], [Singer], [Actor] FROM
(
SELECT ROW_NUMBER() OVER (PARTITION BY Occupation ORDER BY Name) ROW_NO,
ISNULL(NULL,Name) as Name, Occupation
FROM Occupations
) AS t
PIVOT(
MAX(Name)
FOR Occupation IN (
[Doctor],
[Professor],
[Singer],
[Actor]
)
) AS pivot_table
ORDER BY ROW_NO;
I tried this in Oracle, seemed easier to comprehend:
SELECT min(Doctor), min(Professor), min(Singer), min(Actor)
FROM
( Select
ROW_NUMBER() OVER (PARTITION BY Occupation order by Name) rn,
CASE
WHEN Occupation = 'Doctor' then Name
end as Doctor,
CASE
WHEN Occupation = 'Professor' then Name
end as Professor,
CASE
WHEN Occupation = 'Singer' then Name
end as Singer,
CASE
WHEN Occupation = 'Actor' then Name
end as Actor
from OCCUPATIONS
order by Name) a
group by rn
order by rn;
You just need to give each name a row number based on their occupation and order alphabetically.. then include that row number in your pivot query.
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
-- Edit: We need to enclose the subquery after PIVOT within parenthesis "()" to make it work on SQL Server.