I have following table as below:
Structure:
ArticleId INT,
Name varchar(100),
NameId INT
Sample data:
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);