答案 0 :(得分:0)
一个解决方案,继续N:
select distinct f1.parentfk, f2.Quantity , f3.Quantity, f4.Quantity, f5.Quantity
from mytable f1
left outer join mytable f2 on f1.parentfk=f2.parentfk and f2.itemfk=1
left outer join mytable f3 on f1.parentfk=f3.parentfk and f3.itemfk=2
left outer join mytable f4 on f1.parentfk=f4.parentfk and f4.itemfk=3
left outer join mytable f5 on f1.parentfk=f5.parentfk and f5.itemfk=4
或尝试此动态查询:
DECLARE @columns NVARCHAR(MAX), @sql NVARCHAR(MAX);
SET @columns = N'';
SELECT @columns += N', p.' + QUOTENAME(itemfk) FROM (SELECT distinct f2.itemfk FROM Mytable f2) AS x;
SET @sql = N'
SELECT j.ParentFk, ' + STUFF(@columns, 1, 2, '') + '
FROM
(
SELECT ParentFk, Quantity, itemfk FROM Mytable
) AS j
PIVOT
(
Sum(Quantity) FOR itemfk IN ('
+ STUFF(REPLACE(@columns, ', p.[', ',['), 1, 1, '')
+ ')
) AS p;';
PRINT @sql;
EXEC sp_executesql @sql;