an ex-colleague of mine made a query to create pivot tables. I understand how it works if I use one table (MSM_WRKCTRSETUP):
DECLARE @cols AS NVARCHAR(max) = Stuff((SELECT DISTINCT ', ' + Quotename(SKILLRELATION)
FROM MSM_WRKCTRSETUP
where SKILLRELATION <> ''
FOR xml path(''), type).value('.', 'NVARCHAR(MAX)'), 1, 1, '');
DECLARE @maxCols AS NVARCHAR(max) = Stuff((SELECT DISTINCT ', max(' + Quotename(SKILLRELATION) + ') as ' + Quotename(SKILLRELATION)
FROM MSM_WRKCTRSETUP
where SKILLRELATION<> ''
FOR xml path(''), type).value('.', 'NVARCHAR(MAX)'), 1, 1, '');
DECLARE @query AS NVARCHAR(max) = 'SELECT fat.ROUTERELATION, '+@maxCols+'
FROM (SELECT ROUTERELATION, '+ @cols +'
FROM MSM_WRKCTRSETUP A
PIVOT(Max(A.WRKCTRDEFAULTACCOUNTNUM) FOR A.SKILLRELATION IN ('+ @cols +')) piv) fat
group by fat.ROUTERELATION';
EXECUTE(@query)
This is the result: currentOutput
But instead of A.WRKCTRDEFAULTACCOUNTNUM I want to JOIN some tables on the source table to create my desired output: desiredOutput = A.WRKCTRDEFAULTACCOUNTNUM + '-' + C.NAME + ' ( ' + D.LOCATOR + ' ) '
This is the query that needs to be added to the existing query but I don't know where to put it (and how) and I will end up getting errors of columns that are found multiple times or ambiguous names:
LEFT JOIN VENDTABLE B ON
A.WRKCTRDEFAULTACCOUNTNUM = B.ACCOUNTNUM
AND UPPER(A.DATAAREAID) = UPPER(B.DATAAREAID)
LEFT JOIN AR_DIRPARTYVIEW C ON
C.PARTY = B.PARTY
LEFT JOIN AR_DirPartyElectronicAddressView D ON
D.PARTY = B.PARTY
AND D.TYPE = 1
Any ideas how retrieve my desired output? Many thanks in advance!