I have two related sql server tables … TableA and TableB.
***TableA - Columns***
TableA_ID INT
VALUE VARCHAR(100)
***TableB - Columns***
TableB_ID INT
TableA_ID INT
VALUE VARCHAR(100)
For every single record in TableA there are always 2 records in TableB. Therefore TableA has a one-to-many relationship with TableB.
How could I write a single sql statement to join these tables and return a single row for each row in TableA that includes:
- a column for the VALUE column in the first related row in table B
- a column for the VALUE column in the second related row in table B?
For exactly 2 related records, that’s easy. Join table B twice:
If you have a column in table B that determines what is “first value” and what is “second value”, this gets even easier (and it would work like this for N columns in table B, just add more joins):
A composite index on
TableBover(TableA_ID, Type)helps this join.