Click here to Skip to main content
15,893,190 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a query returning the following
  Name | job profile
---------------------
  a    |  Admin
  b    |  User
  c    |  User
  d    |  Employee
  e    |  Admin
  f    |  Employee


I would like to use PIVOT (if even possible) to make the results like so

Admin | User | Employee
 -------------------------
 a    | b    | d
 e    | c    | f
Posted

 
Share this answer
 
Use a UNION to add more than one PIVOT with aggregates MAX() and MIN().

SQL
DECLARE @Job TABLE (Name CHAR(1), [Job Profile] VARCHAR (10))

INSERT INTO @Job
    (Name, [Job Profile])
VALUES
    ('a', 'ADMIN'),
    ('b', 'USER'),
    ('c', 'USER'),
    ('d', 'EMPLOYEE'),
    ('e', 'ADMIN'),
    ('f', 'EMPLOYEE')

SELECT [ADMIN], [USER], [EMPLOYEE]
FROM (
   SELECT *FROM @Job
) J
PIVOT (
    MAX(Name) FOR [Job Profile] IN ([ADMIN], [USER], [EMPLOYEE])
) Result
UNION
SELECT [ADMIN], [USER], [EMPLOYEE]
FROM (
   SELECT *FROM @Job
) J
PIVOT (
    MIN(Name) FOR [Job Profile] IN ([ADMIN], [USER], [EMPLOYEE])
) Result


Use a Dynamic PIVOT, if you do not know the exact number of Job Profiles.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900