Один способ, как вы могли бы сделать это ... хотя это не так красиво ....
Данные
If (OBJECT_ID('tempdb..#Test') IS NOT NULL) DROP TABLE #Test
create table #Test (UserName nvarchar(20), UserId int, ItemId int, ItemName nvarchar(20));
insert into #Test (UserName, UserId, ItemId, ItemName)
values
('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')
А вот запрос .... дать это выстрел, и дайте нам знать, если это поможет вам
Select UserName,
UserId,
MAX([11]) as "Item1",
MAX([21]) as "ItemName1",
MAX([12]) as "Item2",
MAX([22]) as "ItemName2",
MAX([13]) as "Item3",
MAX([23]) as "ItemName3"
FROM (Select UserName,
UserId,
ItemId,
ItemName,
Concat('1', Row_Number() over (partition by UserId order by UserId)) RN1,
Concat('2', Row_Number() over (partition by UserId order by UserId)) RN2
From #Test) as SRC
PIVOT ( MAX(ItemId) FOR RN1 IN ([11], [12], [13], [14]) ) as piv1
PIVOT ( MAX(ItemName) FOR RN2 IN ([21], [22], [23], [24])) as piv2
GROUP BY UserName, UserId