Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to exclude records with certain values in sql

Tags:

sql

mysql

How to exclude records with certain values in sql (MySQL)

Col1    Col2
-----   -----
A       1
A       20
B       1
C       20
C       1
C       88
D       1
D       20
D       3
D       1000
E       19
E       1

Return Col1 (and Col2), but only if the value in Col2 is 1 or 20, but not if there's also another value (other than 1 or 20)

Desired result:

Col1    Col2
-----   -----
A       1
A       20
B       1

But not C,D and E because there's a value in Col2 other than 1 or 20

I've used fictitious values for Col2 and only two values (1 and 20) but in real there some more.
I can use IN ('1', '20') for the values 1 and 20 but how to exclude if there's also another value in Col2. (there's no range !)

like image 456
John Doe Avatar asked Nov 22 '13 11:11

John Doe


People also ask

How do I SELECT all values except one in SQL?

The SQL EXCEPT operator is used to return all rows in the first SELECT statement that are not returned by the second SELECT statement. Each SELECT statement will define a dataset. The EXCEPT operator will retrieve all records from the first dataset and then remove from the results all records from the second dataset.

How do you restrict data in SQL query?

The SQL LIMIT clause constrains the number of rows returned by a SELECT statement. For Microsoft databases like SQL Server or MSAccess, you can use the SELECT TOP statement to limit your results, which is Microsoft's proprietary equivalent to the SELECT LIMIT statement.

How do I SELECT a specific value in SQL?

To select rows using selection symbols for character or graphic data, use the LIKE keyword in a WHERE clause, and the underscore and percent sign as selection symbols. You can create multiple row conditions, and use the AND, OR, or IN keywords to connect the conditions.


2 Answers

Select col1,col2
From table
Where col1 not in (Select col1 from table where col2 not in (1,20))
like image 141
Mudassir Hasan Avatar answered Oct 29 '22 02:10

Mudassir Hasan


Use SUM()

SELECT
  *
FROM
  t
  INNER JOIN
  (SELECT
     SUM(IF(Col2 IN (1, 20), 1, -1)) AS ranges,
     col1
  FROM
    t
  GROUP BY
     col1
  HAVING
    ranges=2) as counts 
 ON counts.col1=t.col1

Update: while it will work for non-repeated list, it may result in wrong set for table with repeated values (i.e. 1, 20, 20, 1 in column - it will still fit request if repeats are allowed, but you've not mentioned that). For case with repeats where's a way too:

SELECT 
  t.* 
FROM 
  t 
  INNER JOIN 
    (SELECT 
       col1, 
       col2 
     FROM 
       t 
     GROUP BY 
       col1 
     HAVING 
       COUNT(DISTINCT col2)=2 
       AND 
       col2 IN (1, 20)) AS counts 
    ON test.col1=counts.col1

(and that will work in common case too, of course)

like image 24
Alma Do Avatar answered Oct 29 '22 01:10

Alma Do