简体   繁体   中英

Pivot Rows into column and combine with another table

I have TableX as

在此处输入图片说明

And TableY as :-

在此处输入图片说明

I want the desired new table creation as :-

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

MenuName col data from TableX should become pivot cols in the new table. DisplayOrder col is different for both tables and cannot be used to have a join.

Please suggest the pivot sql for this desired output.

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

You can write a dynamic query for columns as:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM