首页 > 解决方案 > SQL Server - 从两个表和一个表中获取数据

问题描述

请参阅下面的表格和数据-

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');

where在表 1 中使用条件@test1,它是Ref与表 2@test2 P_Ref列的列连接。我想要两个表中的所有相关数据以及表中的所有匹配Name@test2

我的查询是 -

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

我得到的输出 -

   Ref    P_Ref    Name
    R1      R1      N1
    R1      R1      N2
    R2      R2      N1
    R2      R2      N2

我在看下面的输出 -

   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

有人可以帮助我如何实现这一目标。

提前致谢

标签: sqlsql-server

解决方案


尝试以下查询

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
  )

推荐阅读