sql - 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
有人可以帮助我如何实现这一目标。
提前致谢
解决方案
尝试以下查询
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
)
推荐阅读
- sql - SQL 表中记录的唯一组合(从节点表中获取边)
- python - 无法使用此代码:平分搜索,找到最佳储蓄率以支付房屋首付
- ajax - WordPress 自定义主题重力形式:ajax = true 不起作用
- angular - JDNConvertibleCalendarDateAdapter 库在 Angular 10 中不兼容
- javascript - Jest 在 ReactJS 应用程序中遇到了意外的令牌
- webpack - Webpack 开发服务器在 css 更改时慢编译顺风
- c++11 - 将 GstVideoFrame 转换为 GstBuffer | 流媒体
- r - R. 根据条件改变新变量
- python - 根据 df2 中的查询比较 2 个 dfs 并在 df1 中附加值
- pytorch - 这两个用于推理的代码与玩具 MNIST 示例有什么区别