Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Combine 2 table with both like and unlike columns

Wondering how I would join tables 1 & 2 to get wanted result query. I have tried to union left and right joins, but the like columns are not lining up as I would hope.

Table 1

|Date|ClientID|ClientName|Revenue|Cost1A|Cost1B|Cost1C|
|----|--------|----------|-------|------|------|------|
|12/13/2021|001|ClientA|100|10|10|0|
|12/13/2021|001|ClientA|250|10|10|0|
|12/13/2021|002|ClientB|2500|10|15|1000|

Table 2

|Date|ClientID|ClientName|Revenue|Cost2|
|----|--------|----------|-------|-----|
|12/13/2021|003|ClientC|100|10|
|12/13/2021|003|ClientC|250|10|
|12/13/2021|001|ClientA|25|10|

Wanted Result
|Date|ClientID|ClientName|Revenue|Cost1A|Cost1B|Cost1C|Cost2|
|----|--------|----------|-------|------|------|------|-----|
|12/13/2021|001|ClientA|100|10|10|0|
|12/13/2021|001|ClientA|250|10|10|0|
|12/13/2021|002|ClientB|2500|10|15|1000|
|12/13/2021|003|ClientC|100||||10|
|12/13/2021|003|ClientC|250||||10|
|12/13/2021|001|ClientA|25||||10|

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Use placeholder value for missing column in UNION – I use Null.

SELECT [Date], ClientID, ClientName, Revenue, Cost1A, Cost1B, Cost1C, Null AS Cost2, "T1" AS Src FROM [Table 1]

UNION SELECT [Date], ClientID, ClientName, Revenue, Null, Null, Null, Cost2, "T2" FROM [Table 2];

Use UNION ALL to retain duplicate records.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading