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

Extract items which appears for all articles occurence

I have following table as below:

Structure:

ArticleId INT, 
Name varchar(100), 
NameId INT

Sample data:

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

ArticleId    Name    NameId      
----------------------------
1            a       100
2            a       100
3            a       100
2            b       200
4            a       100
1            c       300
4            g       400
1            h       500
2            h       500
3            h       500
4            h       500

I would like to get only those Names and their NameIds whom appears among all articles (ArticleId). As given above we have ArticleIds: 1,2,3,4. Names a & h pass the criteria because only them appearing in all articles. From the other hand b,c and g appears only in given articles (not for all).

In the end, the result should be:

a       100
h       500

How can I achieve that?

>Solution :

Using aggregation we can try:

SELECT Name, NameId
FROM yourTable
GROUP BY Name, NameId
HAVING COUNT(*) = (SELECT COUNT(DISTINCT ArticleId) FROM yourTable);

Actually, the above only works if you’re certain that every article ID would appear at least once in the table. It would be much better to assert the count of articles from a table dedicated to holding aritcles, so:

SELECT Name, NameId
FROM yourTable
GROUP BY Name, NameId
HAVING COUNT(*) = (SELECT COUNT(*) FROM articles);
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