我将TableX作为
和TableY: -
我想要创建所需的新表格: -
EntityId,EntityIdentification,DisplayName,AK,AL,AR,AZ,CA,CO,CT ....
TableX中的MenuName col数据应该成为新表中的pivot cols。两个表的DisplayOrder col都不同,不能用于连接。
请为此所需输出建议pivot sql。
答案 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
'
;