Question: We are trying to identify patients that have 2 or more of different codes that are contained in another table. There are about 20 or so codes in the table and the patients must have more than 2 of these codes to meet the criteria. How would you go about writing a statement that takes that into effect? In pseudo-code I suppose I am trying to achieve the following:

SELECT \* FROM table WHERE THERE ARE MORE THAN 2 DIFFERENT CODES THAT MATCH A PARTICULAR ID FROM THE OTHER TABLE

```
127282  49  I10
127282  49  E78.5
127290  116 I10
127306  244 E78.5
127306  244 I10
127306  244 I58
127313  320 I10
127313  320 E78.5
127344  560 E78.5
127367  726 E78.5
127375  782 I10

```

In this example the only thing that should be returned is: 127306

I tried using variation of HAVING but it didn't work as intended.

Answer: 
You want to `join` to the other table, aggregate, and filter:

```
select t.id
from t join
     codes c
     on t.code = c.code
group by t.id
having count(distinct t.code) >= 2;

```
The condition must be set in the HAVING clause like this:

```
select id
from tablename
group by id
having count(distinct code) > 2

```

See the [demo](https://www.db-fiddle.com/f/fnErofeFcwHMqr2pSGdyHv/0).