我的桌子看起来像这样:
+------+-------+-------------+
ID_Loc Type Data
+------+-------+-------------+
ABC RMKS Hello
ABC NAM Joe Smith
ABD NAM Peter Hill
ABD RMKS Bye Bye
ABD NAM Freddy Tall
ABE NAM Loran Bennett
ABE RMKS Bye Bye
ABF NAM Liv Claris
ABF RMKS Bye Bye
+------+-------+-------------+
我需要选择所有ID_Loc WHERE DATA NOT LIKE'Hello'。我试过的时候:
SELECT distinct ID_loc FROM data_full WHERE DATA NOT LIKE '% Hello'
这也选择ID_Loc:'ABC',其中包含Data中的'Hello'。 另外,由于这会影响相当多的行或行,如果我可以将查询指向仅查看使用了类型RMKS的行,那将会很好。
我正在使用MS SQL Server 2008
SQL小提琴地址是: http://sqlfiddle.com/#!6/38130/6
任何帮助都会非常感激。
答案 0 :(得分:6)
如果您需要选择没有与ID_Loc
模式匹配的记录的'%Hello'
值,请执行以下查询:
SELECT ID_loc
FROM data_full
group by ID_Loc
having max(case
when DATA LIKE '%Hello' then 1
else 0
end) = 0;
结果如下:http://sqlfiddle.com/#!6/38130/33
如果您还需要应用Type = 'RMKS'
过滤器,则可以在WHERE
子句(sqlfiddle)中执行此操作:
SELECT ID_loc
FROM data_full
where type = 'RMKS'
group by ID_Loc
having max(case
when DATA LIKE '%Hello' then 1
else 0
end) = 0;
答案 1 :(得分:0)
您需要删除空格,同时添加了RMKS过滤器。
SELECT distinct ID_loc
FROM data_full
WHERE Type= 'RMKS'
and DATA NOT LIKE '%Hello' --'%Hello%' if it can be between other text
编辑:
如果ID_Loc,Type
不是唯一的:
SELECT distinct ID_loc
FROM data_full
WHERE ID_loc NOT IN (SELECT ID_loc FROM data_full WHERE Type= 'RMKS'
and DATA LIKE '%Hello')
答案 2 :(得分:0)
您需要删除空格并按类型
过滤SELECT distinct ID_loc
FROM data_full
WHERE DATA NOT LIKE '%Hello%' And [TYPE] = 'RMKS'
答案 3 :(得分:0)
首先从LIKE
子句中删除空格,然后,您可以使用EXISTS
子句过滤符合条件的结果:
<强>查询强>:
SELECT DISTINCT t.ID_loc
FROM data_full t
WHERE NOT EXISTS (SELECT ID_loc
FROM data_full
WHERE Data LIKE '%Hello' AND ID_loc = t.ID_loc )
AND
EXISTS (SELECT ID_loc
FROM data_full
WHERE Type = 'RMKS' AND ID_loc = t.ID_loc )
<强> Results 强>:
| ID_loc |
|--------|
| ABD |
| ABE |
| ABF |
答案 4 :(得分:0)
使用反向逻辑的简单解决方案,您需要where not exists
SELECT distinct t.ID_loc FROM data_full t
where not exists (
select 1 from data_full t2
where t2.ID_loc=t.ID_loc and t2.type='RMKS' and t2.data like '%Hello')
ORDER BY 1;