Skip to content
Advertisement

Exclude blank column while Joining two SQL server tables

I have set of vehicle parts stored in two tables as per below:

Source Table1:

Vehicle_ID Part1 Part2 Part3 Part4 Part5
1 10 20 30
2 10 20
3 10

Source Table2:

Vehicle_ID Part6 Part7 Part8 Part9 Part10
1 40
2 30 50 60
3 30

Required Table like below:

Vehicle_ID Part1 Part2 Part3 Part4 Part5
1 10 20 30 40
2 10 20 30 50 60
3 10 30

Maximum of the Part column up to 5 only.

I tried Union all statement but that statement is not relevant for excluding blank columns.

Please share your experience to solve my problem .

Advertisement

Answer

You need to unpivot and pivot the rows in both tables.

Data:

Statement:

Result:

Vehicle_ID Part1 Part2 Part3 Part4 Part5
1 10 20 30 40
2 10 20 30 50 60
3 10 30
4 40
5 50
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement