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.
You can refer the below link -
https://asktom.oracle.com/pls/asktom/f?p=100:11:0::::p11_question_id:766825833740
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
'
;
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.