Please see my table and data below -
DECLARE @test1 TABLE (Ref nvarchar(10) NULL, Dates datetime NULL);
INSERT INTO @test1(Ref, Dates)
VALUES
('R1', '2018-10-26'),
('R2', '2018-10-26'),
('R5', null);
DECLARE @test2 TABLE (P_Ref nvarchar(50) null, Name nvarchar(50) null);
INSERT INTO @test2(P_Ref, Name)
VALUES
('R1', 'N1'),
('R1', 'N2'),
('R2', 'N1'),
('R2', 'N2'),
('R3', 'N1'),
('R3', 'N2'),
('R4', 'N2'),
('R5', 'N3'),
('R6', 'N3'),
('R7', 'N4');
I am using where condition in table 1 @test1, it's Ref column join with table 2 @test2 P_Ref column.
I want all the related data from both tables as well as all the matches Name from @test2 table
My query is -
select t1.Ref, t2.P_Ref, t2.Name from
@test1 t1
right join @test2 t2
on t1.Ref = t2.P_Ref
where t1.Dates is not null
The output I am getting -
Ref P_Ref Name
R1 R1 N1
R1 R1 N2
R2 R2 N1
R2 R2 N2
I am looking below output -
Ref P_Ref Name
R1 R1 N1
R1 R1 N2
R2 R2 N1
R2 R2 N2
NULL R3 N1
NULL R3 N2
NULL R4 N2
Could someone please help me how to achieve this.
Thanks in advance