[英]T-SQL selecting records where a field contains a certain keyword from another table
I'm trying to run the below SQL to return records where the "a.PatientCommentText" contains a "bad keyword" as indicated by "b.Keyword" below. 我试图运行下面的SQL以返回记录,其中“ a.PatientCommentText”包含一个“不良关键字”,如下面的“ b.Keyword”所示。 I do not think this is returning everything because the below query only returns 253 records, and the inverse of this (where charindex(b.Keyword, a.PatientCommentText) = 0 returns 7,378 records, but the total count of PES_Data is 9,821. I would expect the sum of the two scenarios to equal the record count of PES_Data. What am I doing wrong? 我不认为这会返回所有内容,因为下面的查询仅返回253条记录,而与此相反(其中charindex(b.Keyword,a.PatientCommentText)= 0返回7,378条记录,但PES_Data的总数为9,821。会期望这两种情况的总和等于PES_Data的记录计数。我在做什么错?
Returns 253 records 返回253条记录
select a.* from PES_Data a
inner join Bad_Keywords b on 1=1
where charindex(b.Keyword, a.PatientCommentText) <> 0
Returns 7,378 records 返回7,378条记录
select a.* from PES_Data a
inner join Bad_Keywords b on 1=1
where charindex(b.Keyword, a.PatientCommentText) = 0
But below returns 9,821 records 但下面返回9,821条记录
select a.* from PES_Data a
You would appear to have some PatientCommentText
values that are NULL
. 您似乎会出现一些NULL
PatientCommentText
值。
Try adding this to your results: 尝试将其添加到您的结果中:
select pd.*
from PES_Data pd
where pd.PatientCommentText is null;
In addition, you may be getting duplicates, for comments that contain more than one "bad word". 此外,对于包含多个“坏词”的注释,您可能会得到重复。 I wouldn't expect the numbers to add up, unless you know there are no duplicates. 我不希望数字加起来,除非您知道没有重复项。
+1 to Gordon Linoff's answer. +1(Gordon Linoff)的答案。
DECLARE @tblA TABLE(Base VARCHAR(100));
DECLARE @tblB TABLE(Reference VARCHAR(100));
-- Total 7 rows
INSERT INTO @tblA VALUES
('abcdaa')
,('bcdeab')
,('cdefbb')
,('defgbc')
,('efghcc')
,('fghddd')
,(NULL)
select count(*) from @tblA where CHARINDEX('aa',Base) <> 0 -- Returns 1
select count(*) from @tblA where CHARINDEX('aa',Base) = 0 -- Returns 5
select count(*) from @tblA where CHARINDEX('aa',Base) IS NULL -- Returns 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.