Skip to content
Advertisement

Joining Multiple Tables with different structures?

I have a dataset in SQL with some tables which I need to join them. There is a main table called ‘main_table’ that consists two parameters (id and name) and one of them is the key ‘id’. main_table, TableA, TableB almost have similar structures, but TableC is a bit different as follows:

I could join the first three tables with the following query:

Which gives me the below table:

But, when I want to ‘LEFT JOIN’ the third table (TableC) in this way, it gives me redundant rows, since there are multiple similar ids in TAbleC. I need a query that handles this case and gives me one row for each id when I join them, something like this:

Advertisement

Answer

There are a couple of ways to achieve this, but perhaps the simplest is as Dale K suggested to PIVOT on tablec before joining to it. To give you an idea how this would work, something along the lines of:

I have given a maximum of 4 index columns, but it is easy to see how to extend. If you need this to be open ended, then you will need to convert this into dynamic SQL.

Please note (because you are relatively new) that I have done the hard work for you (providing statements to create the tables and insert the data). In the future when asking such questions, please either do something similar or use db fiddle. You will get many more people willing to help you, if they don’t have to do so much typing. Please remember that people are giving you their time for free.

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