Question: Suppose I have one table with the following values and columns:

```
ID1 | ID2
1   | 1
2   | 1
3   | 1
4   | 1
4   | 2
3   | 3
4   | 3
4   | 4
4   | 4

```

I'd like to retrieve the ID2 values that belong **exclusively** to records where ID1 = 4. So for the above example, I'd like to see the following response:

```
ID1 | ID2
4   | 2
4   | 4

```

Answer: 
These queries will probably be useful to you for the more general cases (and by general I mean when ID1 is something other than 4):

```
select distinct t1.id1, t1.id2
from T as t1
where not exists (
    select 1
    from T as t2
    where t2.ID1 <> t1.ID1 and t2.ID2 = t1.ID2
)

select t1.id1, count(distinct t1.id2)
from T as t1
where not exists (
    select 1
    from T as t2
    where t2.ID1 <> t1.ID1 and t2.ID2 = t1.ID2
)
group by t1.id1

```
There are a few ways to do this:

```
SELECT t1.id1, t1.id2
  FROM mytable t1
 WHERE t1.id1 = 4
   AND NOT EXISTS ( SELECT 1 FROM mytable t2
                     WHERE t2.id2 = t1.id2
                       AND t2.id1 != 4 );

```

or:

```
SELECT id1, id2 FROM (
    SELECT id1, id2
      FROM mytable
     GROUP BY id1, id2
    HAVING COUNT(*) = 1
) WHERE id1 = 4;

```

or:

```
SELECT id1, id2 FROM (
    SELECT id1, id2, COUNT(*) OVER ( PARTITION BY id2 ) AS cnt
      FROM mytable
) WHERE id1 = 4
    AND cnt = 1;

```