Having a main table and a child table in a Microsoft SQL Server database (2005+), I want to show the user a single table in a grid view which includes rows from the main table and rows from the child table, with the latter one being shown as additional columns.
Please see the following example.
Main table:
ID | Name
---+--------
20 | Thomas
21 | Martin
22 | John
23 | Mike
Child table:
ID | MainID | Key | Value
---+--------+-----+-----------
1 | 20 | X | Apple
2 | 20 | Y | Microsoft
3 | 20 | Z | Goole
4 | 21 | X | Dell
5 | 22 | X | Xing
6 | 22 | Y | LinkedIn
7 | 22 | Z | Cisco
8 | 22 | A | Redhat
9 | 23 | Y | Logitech
10 | 23 | Z | Adobe
Now what I want to generate is an SQL statement that results in the following result set:
ID | Name | X | Y | Z
---+--------+--------+-----------+--------
20 | Thomas | Apple | Microsoft | Google
21 | Martin | Dell | <null> | <null>
22 | John | Xing | LinkedIn | Cisco
23 | Mike | <null> | Logitech | Adobe
I.e. the child rows are transformed as additional columns.
My question is:
Is there a way to achieve this with standard SQL, i.e. without using the PIVOT statement or some XML statements? (because I want to use the query against a VistaDB database, too).
Update 1
Then number of detail keys is variable and not limited to 3 or to "X", "Y" and "Z" as names.
