简体   繁体   English

如何在SQL中使用WHERE语句排除组

[英]How to use WHERE statement in SQL to exclude a group

I have a complex query, but here is the essence of what I'm trying to do 我有一个复杂的查询,但这是我要执行的操作的本质

In a table looking like this: 在这样的表格中:

Col1 Col2  
Bill 0  
Bill 0  
Bill 0  
Bill 1  
Bill 1  
John 1  
John 1  
Jonh 1

The above table has 2 columns. 上表有2列。 I am trying to query the rows that has '1' in all the rows in column 2. Since 'Bill' rows with '0' and '1', bill must be excluded. 我正在尝试查询第2列的所有行中都具有'1'的行。由于'Bill'行具有'0'和'1',因此必须排除bill。 Subquery in the WHERE statement gives more than one result, and doen't work. WHERE语句中的子查询给出了多个结果,并且不起作用。

SELECT t1.Col1
FROM Table1 t1
WHERE t1.Col1 <> (SELECT t1.Col1 FROM Table1 t1 WHERE t1.Col2 <> '0')

Using a form of loop statement in the query would bring a whole new level of headache to my project so I hope any smart person can assist me in my quest. 在查询中使用某种形式的循环语句会给我的项目带来全新的头痛,因此我希望任何聪明的人都可以帮助我完成我的任务。

There are a number of approaches. 有很多方法。 Each one has its merits depending on your RDBMS and whatever you find easiest to read. 每个人都有其优点,这取决于您的RDBMS以及您最容易阅读的内容。 See here for more details about performance and check your execution plans or do some testing to obtain the solution that best suits your needs. 有关性能的更多详细信息,请参见此处 ,并检查执行计划或进行一些测试,以获得最适合您需求的解决方案。

SELECT  *
FROM    Table t1
WHERE   t1.Col1 NOT IN (SELECT t1.Col1 FROM Table1 t1 WHERE t1.Col2 <> '0')

or 要么

SELECT  t1.*
FROM    Table t1
        LEFT JOIN
        (   SELECT  Col1
            FROM    Table
            WHERE   Col2 <> '0'
        ) Exc
            ON exc.Col1 = t1.Col1
WHERE   Exc.Col1 IS NULL

or 要么

SELECT  *
FROM    Table t1
WHERE   NOT EXISTS
        (   SELECT  1
            FROM    Table t2
            WHERE   t2.Col2 <> '0'
            AND     t1.Col1 = t2.Col1
        )
SELECT t1.Col1 
FROM Table1 t1 
WHERE NOT EXISTS
(SELECT t2.Col1 
FROM Table1 t2
WHERE t2.col2 = 0
AND t2.col1 = t1.col1)
SELECT Col1
  FROM YourTable
 WHERE Col2 = 1
EXCEPT
SELECT Col1
  FROM YourTable
 WHERE Col2 <> 1;

Try: 尝试:

SELECT Col1 
FROM Table1
GROUP BY Col1
HAVING COUNT(DISTINCT Col2)=1 and MAX(Col2)='1'

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

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