我有两张帐户信息表。第一个表 T1 包含所有产品系列的说明以及提交编号,名称,地区,状态,policynumber等等。第二个表 T2 仅包含与
我需要比较这两个表,并在第二个表T2 中找到Property行的缺失策略编号。我尝试了下面的代码,我得到了列表,但我看到了空值。我该如何从结果中消除这些空值?
SELECT a.[Master Policy Number]
FROM DB1.dbo.Global_Submission_Log AS a
WHERE
a.[Master Policy Number] NOT IN (
SELECT b.PolNo
FROM DB1.dbo.PROPERTY_Files AS b
WHERE b.PolNo = a.[Master Policy Number]
AND a.[Master Policy Number] IS NOT NULL
)
答案 0 :(得分:2)
您可以将is not null
移到子查询之外。您已经有一个=
条件,它将排除空值。
Select a.[Master Policy Number]
From DB1.dbo.Global_Submission_Log a
Where a.[Master Policy Number] Not In (Select b.PolNo
From DB1.dbo.PROPERTY_Files b
Where b.PolNo = a.[Master Policy Number])
And a.[Master Policy Number] Is Not Null
答案 1 :(得分:1)
Select a.[Master Policy Number]
From DB1.dbo.Global_Submission_Log a
Where a.[Master Policy Number] Not In (Select b.PolNo
From DB1.dbo.PROPERTY_Files b
Where b.PolNo = a.[Master Policy Number]
)
/* filter nulls on main query */ And a.[Master Policy Number] Is Not Null
答案 2 :(得分:0)
如果您要过滤掉NULL
值,那么该过滤器应该在外部查询中,而不是在内部查询中:
Select a.[Master Policy Number]
From DB1.dbo.Global_Submission_Log a
Where a.[Master Policy Number] Is Not Null and
a.[Master Policy Number] Not In (Select b.PolNo
From DB1.dbo.PROPERTY_Files b
Where b.PolNo = a.[Master Policy Number]
);
哦,这很奇怪。您正在比较相关子句中使用的NOT IN
的相同列。出于这个原因以及NOT IN
的语义,您应该使用NOT EXISTS
代替。
我应该注意带有子查询的NOT IN
是危险的。如果b.PolNo
曾 NULL
,则NOT IN
永远不会返回true。我的建议是改为使用NOT EXISTS
:
Select gsl.[Master Policy Number]
From DB1.dbo.Global_Submission_Log gsl
Where gsl.[Master Policy Number] Is Not Null and
not exists (select 1
from DB1.dbo.PROPERTY_Files pf
where pf.PolNo = gsl.[Master Policy Number]
);
请注意,如果表别名是表本身的缩写,我还认为查询更容易理解。
答案 3 :(得分:0)
如果您的结果是显示null列表的结果,则可以使用delete from
删除结果。
delete from DB1.dbo.Global_Submission_Log
Where [Master Policy Number] in
(
Select a.[Master Policy Number]From
DB1.dbo.Global_Submission_Log a
Where a.[Master Policy Number] Not In (Select b.PolNo From DB1.dbo.PROPERTY_Files b Where b.PolNo = a.[Master Policy Number]
And a.[Master Policy Number] Is Not Null)
)
答案 4 :(得分:0)
你尝试过加入吗?
Select T1.[Master Policy Number]
From DB1.dbo.Global_Submission_Log T1
LEFT JOIN DB1.dbo.PROPERTY_Files T2
ON T1.[Master Policy Number] on T2.PolNo
Where b.PolNo IS NULL
这将为您提供Property_Files表中但不存在于Global_Submission表中的策略编号