I have a table that looks like the following:
PersonId EyeColor HairColor FavoriteTVShow FavoriteMovie FavoriteFood BirthInfo
---------- ----------- ------------ ------------------- ---------------- --------------- ------------------
A123 Brown Black The Price Is Right NULL Pizza New York City
A444 NULL Brown Friends Elf Steak Seattle
My desired result set is this:
PersonId ColorInfo FavoriteInfo BirthInfo
-------- --------- ------------------ -------------
A123 Brown The Price Is Right New York City
A123 Black Pizza NULL
A444 Brown Friends Seattle
A444 NULL Elf NULL
A444 NULL Steak NULL
So for each PersonId, each group of columns (2 ColorInfo cols, 3 FavoriteInfo cols, and 1 BirthInfo col) is transposed into rows. I've tried variations of CROSS APPLY
and UNPIVOT
, but I can't seem to get it just right. I know it's a weird request, but can anyone think of a good way to do this?
Thank you in advance!
Here's the T-SQL:
--Create the table
CREATE TABLE #test (
PersonId VARCHAR(10),
EyeColor VARCHAR(20),
HairColor VARCHAR(20),
FavoriteTVShow VARCHAR(30),
FavoriteMovie VARCHAR(30),
FavoriteFood VARCHAR(30),
BirthInfo VARCHAR(30)
)
--Populate the table
INSERT INTO #test
VALUES
('A123', 'Brown', 'Black', 'The Price Is Right', NULL, 'Pizza', 'New York City'),
('A444', NULL, 'Brown', 'Friends', 'Elf', 'Steak', 'Seattle')
--See the original result set.
SELECT *
FROM #test
--My desired result set
SELECT *
FROM ( VALUES ('A123', 'Brown', 'The Price Is Right', 'New York City'),
('A123', 'Black', 'Pizza', NULL),
('A444', 'Brown', 'Friends', 'Seattle'),
('A444', NULL, 'Elf', NULL),
('A444', NULL, 'Steak', NULL) ) t (PersonId, ColorInfo, FavoriteInfo, BirthInfo)