I have the following table, and am trying to pivot it so that a new column is created for each item per user, but all users are grouped into one row e.g. if the most items a user has is 4, i would like 4 item columns.
I know that I need to use dynamicSQL and possibly the COALESCE function too, but this doesn't seem to produce the required result.
I need to pivot this:
UserName UserId ItemiD ItemName
----- ---- ------ --------
Bob 445 46 Hat
Bob 445 138 Tshirt
Rachel 512 46 Hat
Rachel 512 59 Mug
Rachel 512 138 Tshirt
Simon 771 46 Hat
Simon 771 400 MouseMat
Into this:
UserName UserId Item1iD Item1Name Item2iD Item2Name Item3iD Item3Name
----- ---- ------ -------- ------- -------- ------- --------
Bob 445 46 Hat 138 Tshirt NULL NULL
Rachel 512 46 Hat 59 Mug 138 Tshirt
Simon 771 46 Hat 400 MouseMat NULL NULL
Many thanks