I have a table like the below
Opp_ID Role_Name Role_User_Name
---------------------------------------
1 Lead Person_one
1 Developer Person_two
1 Developer Person_three
1 Owner Person_four
1 Developer Person_five
I now need to split the Role_Name column to be 3 different columns based on the values. I need to make sure there are no NULL values so the table should like the below
Opp_ID Lead Developer Owner
--------------------------------------------------
1 Person_one Person_two Person_four
1 Person_one Person_three Person_four
1 Person_one Person_five Person_four
My code is currently:
SELECT
ID,
CASE WHEN Role_Name = 'Lead' THEN Role_User_Name ELSE NULL END AS Lead,
CASE WHEN Role_Name = 'Developer' THEN Role_User_Name ELSE NULL END AS Developer,
CASE WHEN Role_Name = 'Owner' THEN Role_User_Name ELSE NULL END AS Owner
FROM
[table1]
WHERE
Role_Name IN ('Lead','Developer','Owner')
Unfortunately this returns these results:
Opp_ID Lead Developer Owner
-------------------------------------------
1 Person_one NULL NULL
1 NULL Person_two NULL
1 NULL Person_three NULL
1 NULL NULL Person_four
1 NULL Person_five NULL
I assume to get this working you need to join the code back on itself but I can't seem to get it working.
PIVOToperation, but how that is accomplished will depend on the database you are using.ELSE NULLwhy don't you putELSE Role_User_Name? Also what should be the result in the NULL values of Developer in your last example?PIVOTbut a couple of self-JOINs.