简体   繁体   中英

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. 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. Subquery in the WHERE statement gives more than one result, and doen't work.

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. 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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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