SQL Server - Get data from two tables and within a table

Viewed 65

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

4 Answers

Try the following query

SELECT t1.Ref, t2.P_Ref, t2.Name
FROM @test1 t1
RIGHT JOIN @test2 t2 ON t1.Ref = t2.P_Ref
WHERE t2.Name IN(
    SELECT DISTINCT t2.Name
    FROM @test1 t1
    JOIN @test2 t2 ON t1.Ref = t2.P_Ref
    WHERE t1.Dates IS NOT NULL
  )

Try the below query

select t1.Ref, t2.P_Ref, t2.Name from
@test1 t1 right join @test2 t2
on t1.Ref = t2.P_Ref
where Name in ('N1', 'N2')

If there are large number of records expected whose Dates may not be NULL then an optimized option will be as below.

IF OBJECT_ID('tempdb..#ValidRecords') IS NOT NULL
    DROP TABLE #ValidRecords

SELECT DISTINCT t2.[Name]
INTO #ValidRecords
FROM @test1 t1
JOIN @test2 t2 ON t1.Ref = t2.P_Ref
WHERE t1.Dates IS NOT NULL

SELECT Ref,
t2.P_Ref,
t2.[Name]
FROM @test1 t1
RIGHT JOIN @test2 t2 ON t1.Ref = t2.P_Ref
INNER JOIN #ValidRecords vr ON vr.[Name] = t2.[Name]

The problem is that your WHERE clause is turning your outer join into an implicit inner join. To filter the outer table, it's usually easiest to move the filter condition for the outer table to the join condition.

select t1.Ref, t2.P_Ref, t2.Name from
@test1 t1
right join @test2 t2
    on  t1.Ref = t2.P_Ref
    and t1.Dates is not null
Related