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

Finding the id's which include multiple criteria in long format

Suppose I have a table like this,

id tagId
1 1
1 2
1 5
2 1
2 5
3 2
3 4
3 5
3 8

I want to select id‘s where tagId includes both 2 and 5. For this fake data set, It should return 1 and 3.

I tried,

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

select id from [dbo].[mytable] where tagId IN(2,5)

But it takes 2 and 5 into account respectively. I also did not want to keep my table in wide format since tagId is dynamic. It can reach any number of columns. I also considered filtering with two different queries to find (somehow) the intersection. However since I may search more than two values inside the tagId in real life, it sounds inefficient to me.

I am sure that this is something faced before when tag searching. What do you suggest? Changing table format?

>Solution :

One option is to count the number of distinct tagIds (from the ones you’re looking for) each id has:

SELECT   id
FROM     [dbo].[mytable] 
WHERE    tagId IN (2,5)
GROUP BY id
HAVING   COUNT(DISTINCT tagId) = 2
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