简体   繁体   中英

ORACLE / Select the records that only has the value X on Column_B

I have the following scenario:

Table1

ID  Column_B
10001   X
10001   Y
10002   X
10003   X
10003   Y
10004   X
10005   X
10005   Y

I need to do a query that shows the IDs that has only X on Column_B, so the result would be:

10002   X
10004   X

If I run the select below, it shows also the records that has Y on Column_B:

select ID, Column_B from Table1 where Column_B = 'X'

ID  Column B
10001   X
10002   X
10003   X
10004   X
10005   X

I couldn't find anything similar to this case, anywhere. Losing my mind here trying to figure it out. It seems to be so simple. Damn.

You can use aggregation:

select id
from t
group by id
having min(column_b) = max(column_b) and min(column_b) = 'X';

Use relational algebra - in this case, MINUS :

SELECT ID
  FROM TABLE1
  WHERE COLUMN_B = 'X'
MINUS
  SELECT ID
    FROM TABLE1
    WHERE COLUMN_B = 'Y';

You start with a list of all the ID's which are associated with 'X', and subtract off the list of ID's which are associated with 'Y'.

SQLFiddle here

Best of luck.

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