简体   繁体   中英

SQL DB2: Need to select all records belonging to a client having a unique value in column B (value = P)

Need to select all records belonging to a client having a unique value in column B (value = P)

Here is my DB2 Table:

Name      Column B

David         P
David         P
Stacy         A
Stacy         A
Curry         A
Curry         P
Curry         P
Kevin         P
Kevin         P

Result expected:

 Name Column B David P David P Kevin P Kevin P

If there aren't any nulls in ColumnB you can use NOT EXISTS :

select t.* from tablename t
where not exists (select 1 from tablename where Name = t.Name and ColumnB <> 'P')  

See the demo .
Results:

>  NAME | COLUMNB
> ----: | ------:
> David |       P
> David |       P
> Kevin |       P
> Kevin |       P

Based on your question, you seem to want:

select t.*
from t
where t.b = 'P' and
      not exists (select 1 from t t2 where t2.name = t.name and t2.b <> 'P');

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