Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

SQL Group By, match list of values

I have a table like below:

tbl:

id device_id device_model
1 101 A
1 201 B
1 202 B
2 102 A
2 301 C
3 103 A
3 203 B
3 302 C

I want to select group of ids with specific device_models given with a list.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

At first, I tried:

SELECT id
FROM tbl
WHERE device_model IN ('A', 'B')
GROUP BY id

But this works like OR, if an id has only one of ('A', 'B'), then it is returned. This is not the behaviour I want, instead I want an AND behaviour.

Then, I thought I can use this:

SELECT id
FROM tbl
WHERE device_model IN ('A', 'B')
HAVING COUNT(DISTINCT device_model) = 2;

But, this returns ids 1 and 3, but I only want 1 because group with id == 3 also has device_model C.

What can I do to get ids that has only ALL given device_models using a list?

>Solution :

Add the GROUP BY clause and one more condition inside the HAVING clause, that checks the presence of only A,B inside the field device_model.

SELECT id
FROM tbl
GROUP BY id
HAVING COUNT(DISTINCT device_model) = 2
   AND MIN(device_model IN ('A', 'B')) = 1;

This should work on MySQL, and should generalize well on any n amount of elements you want to check. It would suffice to add all your elements inside the array, and update the number of distinct elements.

Output:

id
1

Check the demo here.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading