简体   繁体   中英

Select a row with just one value in a table

This is my table looks:

(I don't say it before, colum2 is string type, not an integer, sorry about it)

╔══════╦═══════╗
║ USER ║ COLOR ║
╠══════╬═══════╣
║ a    ║ Red   ║
║ b    ║ Blue  ║
║ c    ║ Blue  ║
║ b    ║ Red   ║
║ a    ║ Red   ║
║ c    ║ White ║
╚══════╩═══════╝

I've just need the rows which has exclusively color= "Red".
It must return "a" ("b" contains value "Blue" too).

How can I set the select? Thanks and regards

SELECT  column1
FROM    TableName
GROUP   BY Column1
HAVING  COUNT(DISTINCT column2) = 1
        AND MAX(column2) = 1

here's another way,

SELECT  column1
FROM    TableName
GROUP   BY Column1
HAVING  MAX(column2) = MIN(column2) AND
        MAX(column2) = 1

UPDATE 1

SELECT  user
FROM    TableName
GROUP   BY user
HAVING  SUM(color = 'red') = COUNT(*)

The more efficient way to do this is by comparing the min and max values:

select column1
from t
group by column1
having min(column2) = max(column2) and min(column2) = 1

If the column can take on NULL values, you will need to exclude those as well:

select column1
from t
group by column1
having min(column2) = max(column2) and min(column2) = 1 and count(column2) = count(*)
Select distinct Column1 from Table1 Where Column2='1'

Or if it is integer then:

Select distinct Column1 from Table1 Where Column2=1

Assuming that Table1 is the table name

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