Skip to content
Advertisement

Join Two Tables Then Transpose Rows From One Table As Column Names

I’m trying to join two tables

and then transposing rows of data (from Name on ColumnNames table) as column names.

Now, I was told to use Pivot. I’ve successfully used pivot for transposing rows from a single table, but I’m confused in how to transpose rows from joined tables.

Below is the code that I’ve tried, but it gives me an error saying columns doesn’t exist

Expected Result Should be

Am I utilizing pivot correctly on this scenario?

Advertisement

Answer

Consider a ranking with ROW_NUMBER across each column value type (fullname, email, position, category) to be included in INNER JOIN then run through PIVOT. No need of dynamic building of SQL:

Rextester demo

For a dynamic query, build a @cols string to place in specific places of pivot query.

Rextester demo

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement