0

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!

  • please put your existing output and desired output – Venkataraman R Apr 26 '21 at 09:02
  • For a joined pivot, you need to make a derived table or CTE to pivot on. Start by writing a static (non-dynamic) pivot and you will understand how it is done, then you can write a dynamic one. This code doesn't work anyway because the third parameter of `STUFF` (the second `1`) needs to be the length of the joining text, so `@cols` should have `, 1, 2, '');` and `@maxCols` should have `, 1, 6, '');` – Charlieface Apr 26 '21 at 09:36
  • Thanks @Charlieface for the suggestion of the similar question, I built a static pivot, which serves my purpose for now. May do a dynamic one later. – Tamerlaaane Apr 28 '21 at 14:22

0 Answers0