选择行到列

时间:2017-06-05 09:40:20

标签: sql-server select sql-server-2008-r2

我有以下表格:

MyTable

但需要选择以下结果,另外请注意可能没有固定项目!!

Result

1 个答案:

答案 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;