提问人:Data Engineer 提问时间:3/30/2021 最后编辑:ekocherginData Engineer 更新时间:3/31/2021 访问量:32
SQL 中的 OR 和 AND 返回不应显示的结果
OR and AND in SQL returns results which should not appear
问:
我需要获得的结果仅包括以下组合在特定日期范围内出现和更新的标题。问题在于下面的代码仍然返回许多其他不在搜索条件下的标题。
输出如下所示,很明显代码有问题。所需的输出不返回此标题
USE My DB;--[dbo].[fn_StripCharacters]
;with cte_All as (
SELECT
--top 100
ID,
t.LastNameTx,
t.FirstName,
MyDB.[dbo].[fn_StripCharacters] (t.Title, '^a-z') as Stripped_Title,
t.Title,
t.City,
t.State,
t.VerificationDate,
t.VerifiedBy,
t.ModificationDate,
t.ModifiedBy,
'Higher Importance' AS Importance
FROM
My.dbo.MyTable t WITH (NOLOCK)
),
cte_TitleExceptions as (
SELECT
--top 100
ID,
t.LastNameTx,
t.FirstName,
MyDB.[dbo].[fn_StripCharacters] (t.Title, '^a-z') as Stripped_Title,
t.Title,
t.City,
t.State,
t.VerificationDate,
t.VerifiedBy,
t.ModificationDate,
t.ModifiedBy,
'Higher Importance' AS Importance
FROM
cte_All gc WITH (NOLOCK) -- ISCore.dbo.GovContact gc WITH (NOLOCK)
WHERE
COALESCE(CONVERT(DATE, t.VerificationDate),CONVERT(DATE, t.ModificationDate)) < DATEADD(m, -12, @DateInPast)
AND COALESCE(CONVERT(DATE, t.VerificationDate),CONVERT(DATE, t.ModificationDate)) != CAST(GETDATE() AS DATE) --@DateInPast
AND (
-- list of exeptions from Williamson Remot
-- gc.Stripped_Title LIKE '%Director%'
gc.Stripped_Title LIKE '%Human%'
OR gc.Stripped_Title LIKE '%HR%'
OR gc.Stripped_Title LIKE '%ITDirector%'
OR gc.Stripped_Title LIKE '%ITOfDirector%'
OR gc.Stripped_Title LIKE '%DirectorIT%'
OR gc.Stripped_Title LIKE '%DirectorOfIT%'
OR gc.Stripped_Title LIKE '%InformationTechnolog%'
OR gc.Stripped_Title LIKE '%Finance%'
OR gc.Stripped_Title LIKE '%CFO%'
OR gc.Stripped_Title LIKE '%ChiefFinancialOfficer%'
OR gc.Stripped_Title LIKE '%FinancialOffice%'
OR gc.Stripped_Title NOT LIKE '%Engineer%'
)
)
select
*
from
cte_TitleExceptions
答:
2赞
eshirvana
3/30/2021
#1
您的 OR 语句存在缺陷
...
OR gc.Stripped_Title NOT LIKE '%Engineering%'
OR gc.Stripped_Title NOT LIKE '%Engineer%'
...
你基本上是在说返回所有不像“%Engineer%”的东西,所以上面的所有陈述都是无用的
如果我理解正确的话,你的代码应该是这样的:
...
AND (
-- list of exeptions from Williamson Remot
-- gc.Stripped_Title LIKE '%Director%'
gc.Stripped_Title LIKE '%Human%'
OR gc.Stripped_Title LIKE '%HR%'
OR gc.Stripped_Title LIKE '%ITDirector%'
OR gc.Stripped_Title LIKE '%ITOfDirector%'
OR gc.Stripped_Title LIKE '%DirectorIT%'
OR gc.Stripped_Title LIKE '%DirectorOfIT%'
OR gc.Stripped_Title LIKE '%InformationTechnolog%'
OR gc.Stripped_Title LIKE '%Finance%'
OR gc.Stripped_Title LIKE '%CFO%'
OR gc.Stripped_Title LIKE '%ChiefFinancialOfficer%'
OR gc.Stripped_Title LIKE '%FinancialOffice%'
)
AND (
gc.Stripped_Title NOT LIKE '%Engineer%'
-- these two can be combined to one
)
...
评论
0赞
Data Engineer
3/30/2021
@eshirvana 不知道为什么我应该说 NOT LIKE 我需要使用 LIKE 来返回我的搜索 sondition 中的标题
1赞
eshirvana
3/30/2021
@enigma6205我什么也没说,你用了 NOT LIKE !,请参阅您的代码。
0赞
Data Engineer
3/30/2021
如果某物有人类,需要返回此记录。但是,如果磁贴不在 where 子句中提供的任何其他标题中,则不需要返回它。
0赞
eshirvana
3/30/2021
那么它不是,请参阅我答案的第二部分AND
OR
0赞
eshirvana
3/30/2021
@enigma6205你是welocome,如果有帮助,请接受作为答案
评论