简体   繁体   English

如何从查询中排除某些条目 [SQL]

[英]How to exclude certain entries from a query [SQL]

I do have the following issue: Let's say you have a table that looks like this:我确实有以下问题:假设您有一个如下所示的表:

"ExampleTable"

NotPrimID     Number
0             13
0             13
0             14
1             14
1             14
2             13
2             13

Question : I want to have an query which will deliver all the NotPrimID 's which do have the Number as 13, however if the Number of a NotPrimID is also 14 etc. it should be automatically excluded from the list.:我想有一个query ,这将提供所有的NotPrimID的其中确实有Number为13,然而,如果Number一的NotPrimID也是14等,应该从列表中自动排除。

If you just want the ids, then use group by and having :如果您只想要 ID,请使用group byhaving

select notprimid
from t
where number in (13, 14)
group by notprimid
having max(number) = 13;  -- has 13 but not 14

If you want the original rows, one method is exists / not exists :如果你想要原始行,一种方法是exists / not exists

select t.*
from t
where exists (select 1 
              from t t2
              where t2.notprimid = t.notprimids and
                     t2.number = 13
             ) and
      not exists (select 1 
                  from t t2
                  where t2.notprimid = t.notprimids and
                        t2.number = 14
                 );

You could use exists logic here:您可以在此处使用存在逻辑:

SELECT DISTINCT NotPrimID
FROM ExampleTable t1
WHERE Number = 13 AND NOT EXISTS (SELECT 1 FROM ExampleTable t2
                                  WHERE t2.NotPrimID = t1.NotPrimID AND t2.Number = 14);

Demo 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM