Click here to Skip to main content
15,902,846 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Consider the below two tables.
TABLE A
Order  invoice  date       quantity  cust_code
111     45     20/08/2017   9          abc
112     32     21/08/2017   4          abc
113     42     22/08/2017   5          abc
114     49     20/08/2017   5          abc

TABLE B
Order   date       quantity
 111     20/08/2017   3
 111     20/08/2017   6
 113     22/08/2017   5
 49      20/08/2017   5
 112     21/08/2017   4


Now in table B the values in Order column can either be the order column from table A or the Invoice from table A. I want to join the tables in such a way that i add the missing columns in table B from table A.

Expected result


Order   date       quantity  Invoice
 111     20/08/2017   3       45
 111     20/08/2017   6       45
 113     22/08/2017   5       42
 49      20/08/2017   5       49
 112     21/08/2017   4       32


What I have tried:

select * 
from Table B  d2
left join Table A d1 on d2.Invoice =d1.order 


This only matches the order column. So in expect result table Row 4, in invoice column it will say null, i do not want that. if the order column does not match then i want it to check the invoice column.
Posted
Updated 14-Aug-17 5:12am

1 solution

So add a criteria to your JOIN condition:
SQL
SELECT b.[Order], b.[Date],  b.Quantity, a.Invoice
FROM TableB  b
LEFT JOIN TableA a ON b.[Order] = a.[order] OR b.[Order] = a.Invoice
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900