I have a table view T like:

id | C1   | C2  |
---+------+-----+
1  | pat  | 190 |
1  | pat1 | 191 |
1  | A5   | 302 |
2  | pet  | 190 |
2  | pet1 | 191 |
2  | A5   | 302 |
3  | pit  | 190 |
3  | pit1 | 191 |
3  | A6   | 302 |

Would like to get:

id | C1   | C2  |
---+------+-----+
1  | pat  | 190 |
2  | pet  | 190 |

In other words, return id where C2 = 190 where same id elsewhere in table is A5.

Have tried several LEFT JOIN approaches but haven't gotten anywhere. Please help. Thanx.

2 Answers

2
forpas On Best Solutions

You need EXISTS:

select t.*
from tablename t
where c2 = 190
and exists (
  select 1 from tablename where id = t.id and c1 = 'A5'
)

See the demo.
Results:

| id  | C1  | C2  |
| --- | --- | --- |
| 1   | pat | 190 |
| 2   | pet | 190 |
0
sticky bit On

You can use EXISTS to check if a row with c1 = 'A5' exists for an ID.

SELECT *
       FROM t t1
       WHERE t1.c2 = 190
             AND EXISTS (SELECT *
                                FROM t t2
                                WHERE t2.id = t1.id
                                      AND t2.c1 = 'A5');