Skip to content
Advertisement

SQL join rows from second table as columns

This is probably a duplicate question, but I couldn’t find it. Maybe I’m thinking about this backwards.

How do I format a query to return the results like this with the source tables below?

Filename Attr1 Attr2 Attr3 Configuration
file1.txt Val1 Val2 Val3 Default
file1.txt Val1 Val2 Val3 First

Documents Table

DocumentID Filename
1 file1.txt

VariableValues table

VariableID DocumentID ValueCache ConfigurationID
55 1 Val1 1
56 1 Val2 1
172 1 Val3 1
55 1 Val1 2
56 1 Val2 2
172 1 Val3 2

Configuration Table

ConfigurationID ConfigName
1 Default
2 First

I originally wrote this with subqueries

But that doesn’t handle configurations properly, the subqueries return multiple results when there are multiple configurations. So I tried converting it to a table valued query, but this returns each variable on a separate line and I can’t figure out how to transpose them.

Advertisement

Answer

You can use the PIVOT function on your INNER JOIN query in two scenarios:

1st one: if the number of ValueCache values is known i.e. only (val1, val2, val3)

2nd one: if the number of ValueCache values is unknown then you can use Dynamic SQL Query

See the result form dbfiddle.

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