Pivot Rows into column并与另一个表组合

时间:2014-04-21 08:12:24

标签: sql sql-server

我将TableX作为

enter image description here

和TableY: -

enter image description here

我想要创建所需的新表格: -

EntityId,EntityIdentification,DisplayName,AK,AL,AR,AZ,CA,CO,CT ....

TableX中的MenuName col数据应该成为新表中的pivot cols。两个表的DisplayOrder col都不同,不能用于连接。

请为此所需输出建议pivot sql。

3 个答案:

答案 0 :(得分:0)

答案 1 :(得分:0)

select EntityId, EntityIdentification, DisplayName, AK, AL, AR, AZ, CA, CO, CT from 
    (select  EntityId, EntityIdentification, DisplayName, GlobalMenuID,MenuName from TableX X
    join TableY Y on X.DisplayOrder=Y.DisplayOrder) as Source
    PIVOT (SUM(GlobalMenuID) for MenuName  in (AK, AL, AR, AZ, CA, CO, CT) )
    as pivot

答案 2 :(得分:0)

您可以为列编写动态查询:

DECLARE @columns NVARCHAR(MAX)
       ,@sql NVARCHAR(MAX);

SET @columns = N'';
--Get column names for entire pivoting
SELECT @columns += N', ' + QUOTENAME(SpreadCol)
  FROM (select distinct MenuName as SpreadCol 
        from tblX
       ) AS T;  
select @columns;

--and then PIVOT to get desired result as:

SET @sql = N'
SELECT entityId, entityIdentification, displayName, ' + STUFF(@columns, 1, 2, '') + '
FROM
(select globalMenuID, entityId, entityIdentification, displayName , menuName as SpreadCol
from tblX inner join tblY on tblY.displayOrder = tblX.displayOrder
) as D
PIVOT
(
  Max(globalMenuID) FOR SpreadCol IN ('
  + STUFF(REPLACE(@columns, ', [', ',['), 1, 1, '')
  + ')
) AS Pivot1
'

;

Check Demo here