Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL select rows with only a certain value in them

I have a table as such

Col 1 Col 2 Col 3
1       A     1
2       A     2
3       B     1
4       C     1
5       C     2
6       D     1

How do I only get unique rows which have Col 3 = 1?

I want to get rows 3 and 6 (Col 2 = B and D respectively). I do not want A nor C since they have Col 3 = 2 as well.

I've tried something along the lines of:

select col 2 from table group by col 2 having count(col 3) = 1

But that only brings up Col 2 for results so I'm uncertain if Col 3 contents = 1 or not.

EDIT: Sorry guys maybe I've not worded my question clearly. I want to get all of the rows of Col 2 which contain only Col 3 = 1 AND ONLY 1.

So if I tried WHERE Col 3= 1, it would return 4 rows because A has 1. But since A also has a row where Col 3 = 2, I do not want that, same for C. From this example table, I would want the end result to only show 2 rows, B and D.

My example table is an example, I actually have about 5000 rows to filter through, otherwise I'd do as you guys have suggested :)

like image 212
MHTri Avatar asked May 24 '11 12:05

MHTri


People also ask

How do I SELECT a row from 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.

How do I SELECT only certain values in a column in SQL?

The column names that follow the select keyword determine which columns will be returned in the results. You can select as many column names that you'd like, or you can use a “*” to select all columns. The table name that follows the keyword from specifies the table that will be queried to retrieve the desired results.

How do I exclude certain rows in SQL?

Use the relational operators != or <> to exclude rows in a WHERE clause.


1 Answers

SELECT col2
FROM your_table
GROUP BY col2
HAVING MAX(col3) = 1 AND MIN(Col3) = 1

Or

SELECT a.col2 
FROM your_table a
WHERE a.col3=1 AND NOT EXISTS(SELECT *
                              FROM your_table b 
                              WHERE a.col2=b.col2 AND b.col3<>1)
like image 96
Martin Smith Avatar answered Sep 17 '22 21:09

Martin Smith