I've never done something like this, and I tried finding it on google but without result.
I have 3 tables that look like this:
Orders:
OdredID (int) PK,
UserID (int) FK,
OdredDate (datetime)
Components:
ComponentID (int) PK,
Name (nvarchar(50)),
Type (nvarchar(max))
OrderComponent:
OrderComponentID (int) PK,
OrderID (int) FK,
ComponentID (int) FK,
Value (nvarchar(max))
Lets say one order has 3 components with names: [CPU, Motherboard, Memory]
and values [1GHz, AsusP5, 2GB Kingston DDR3]
I need a result has columns like this:
OrderID UserID Date CPU Motherboard Memory
1 1 2012-05-21 1GHz AsusP5 2GB Kingston DDR3
Basically I need every join row to go as new column with name taken from Name
column of join table and value from Value
column.
Try this:
SQL Fiddle Demo
Note that: This the standard SQL way to do this. But you can use the SQL Server
PIVOT
table operator to do the same thing like so:But this for a set of pre defined values like
[CPU], [Motherboard], [Memory]
.For unknown number of values, you have to do it dynamically like so:
Updated SQL Fiddle Demo