I'm trying to combine two tables using two criterias
- if table 1 referance & amount matched with table 2 referaance & amount join those records
- for the items that were not matched above criteria join based on the table 1 amount match with table 2 amount.
My tables are as follows.
CREATE TABLE [TEST].[dbo].[tb1]
(date DATE , ref INT, amount INT )
INSERT INTO [TEST].[dbo].[tb1] VALUES
('2017-01-01',1000,500),
('2017-01-15',null,500),
('2017-02-01',2000,1000),
('2017-02-15',null,1000)
CREATE TABLE [TEST].[dbo].[tb2]
(date2 DATE , ref2 INT, amount2 INT )
INSERT INTO [TEST].[dbo].[tb2] VALUES
('2017-01-04',1000,500),
('2017-01-20',null,500),
('2017-02-05',2000,1000),
('2017-02-25',null,1000)
How can i achive this
Date Ref Amount Date Ref Amount
1-Jan-17 1000 500 4-Jan-17 1000 500
5-Jan-17 500 10-Jan-17 500
1-Feb-17 2000 1000 5-Feb-17 2000 1000
15-Feb-17 1000 25-Feb-17 1000
Code i wrote so;
Select *
from [TEST].[dbo].[tb1] tb1
join [TEST].[dbo].[tb2] tb2
ON (tb1.amount = tb2.amount2 and tb1.ref = tb2.ref2)
union all
Select *
from [TEST].[dbo].[tb1] tb1
join [TEST].[dbo].[tb2] tb2
ON (tb1.amount = tb2.amount2)
Highly appreciate your help on this.