JS List
asked on
TSQL Query Primary Table to a Key Table Joined Back to Primary Table
Hello,
I have a table of keys IDs and a table of Companies with those key IDs.
A company can own many sub-companies in the same table. The key table connects the parent and sub company together.
What query would I used to get something like this:
SELECT co_ID as P_ID, CompanyName as Parent, co_ID as C_ID, CompanyName as Child
The result would look like this:
ParentCompany 1, 1, Null
ParentCompany 2, 2, Null
ParentCompany 3, 3, Null
ParentCompany 1, 1, ChildCompany1ParentCompany 1, 4
ParentCompany 1, 1, ChildCompany2ParentCompany 1, 5
ParentCompany 1, 1, ChildCompany3ParentCompany 1, 6
ParentCompany 2, 2, ChildCompany1ParentCompany 2, 7
ParentCompany 2, 2, ChildCompany2ParentCompany 2, 8
ParentCompany 3, 3, ChildCompany1ParentCompany 3, 9
ParentCompany 3, 3, ChildCompany2ParentCompany 3, 10
ParentCompany 3, 3, ChildCompany3ParentCompany 3, 11
Companies
co_ID Company Name
1 ParentCompany 1
2 ParentCompany 2
3 ParentCompany 3
4 ChildCompany1ParentCompany 1
5 ChildCompany2ParentCompany 1
6 ChildCompany3ParentCompany 1
7 ChildCompany1ParentCompany 2
8 ChildCompany2ParentCompany 2
9 ChildCompany1ParentCompany 3
10 ChildCompany2ParentCompany 3
11 ChildCompany3ParentCompany 3
Key table
kid parentID ChildID
1 1 4
2 1 5
3 1 6
4 2 7
5 2 8
6 3 9
7 3 10
8 3 11
JS
I have a table of keys IDs and a table of Companies with those key IDs.
A company can own many sub-companies in the same table. The key table connects the parent and sub company together.
What query would I used to get something like this:
SELECT co_ID as P_ID, CompanyName as Parent, co_ID as C_ID, CompanyName as Child
The result would look like this:
ParentCompany 1, 1, Null
ParentCompany 2, 2, Null
ParentCompany 3, 3, Null
ParentCompany 1, 1, ChildCompany1ParentCompany
ParentCompany 1, 1, ChildCompany2ParentCompany
ParentCompany 1, 1, ChildCompany3ParentCompany
ParentCompany 2, 2, ChildCompany1ParentCompany
ParentCompany 2, 2, ChildCompany2ParentCompany
ParentCompany 3, 3, ChildCompany1ParentCompany
ParentCompany 3, 3, ChildCompany2ParentCompany
ParentCompany 3, 3, ChildCompany3ParentCompany
Companies
co_ID Company Name
1 ParentCompany 1
2 ParentCompany 2
3 ParentCompany 3
4 ChildCompany1ParentCompany
5 ChildCompany2ParentCompany
6 ChildCompany3ParentCompany
7 ChildCompany1ParentCompany
8 ChildCompany2ParentCompany
9 ChildCompany1ParentCompany
10 ChildCompany2ParentCompany
11 ChildCompany3ParentCompany
Key table
kid parentID ChildID
1 1 4
2 1 5
3 1 6
4 2 7
5 2 8
6 3 9
7 3 10
8 3 11
JS
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
This worked. Thanks for both suggestions.
Open in new window