It's really helpful when you provide demo DDL/DML. It makes it much easier for people to answer your question.
Here's an example:
DECLARE @Prof TABLE (ad_id INT, prof_name VARCHAR(20));
INSERT INTO @Prof (ad_id, prof_name) VALUES
(1, 'Joe'),(2, 'Joe'),(3, 'Joe'),(4, 'Joe'),(5, 'Joe'),
(1, 'Bill'),(2, 'Bill'),(3, 'Bill'),(4, 'Bill'),
(1, 'John'),(2, 'John'),(3, 'John'),(4, 'John'),
(1, 'Mick'),(2, 'Mick'),(3, 'Mick'),
(1, 'Ringo'),(2, 'Mick'),(3, 'Joe');
Using this, we can demonstrate the difference between COUNT()
and COUNT(DISTINCT )
:
SELECT ad_id, COUNT(prof_name) AS Cnt, COUNT(DISTINCT prof_name) AS dCnt
FROM @Prof
GROUP BY ad_id
ad_id |
Cnt |
dCnt |
1 |
5 |
5 |
2 |
5 |
4 |
3 |
5 |
4 |
4 |
3 |
3 |
5 |
1 |
1 |
Now, if we want just the rows from the table which have a distinct count of 4 (inferred from your description), we can use a CTE
to get those, and join them to the table:
;WITH IDs AS (
SELECT ad_id, COUNT(prof_name) AS Cnt, COUNT(DISTINCT prof_name) AS dCnt
FROM @Prof
GROUP BY ad_id
HAVING COUNT(DISTINCT prof_name) = 4
)
SELECT p.ad_id, p.prof_name
FROM @Prof p
INNER JOIN IDs i
ON p.ad_id = i.ad_id
ad_id |
prof_name |
2 |
Mick |
2 |
Mick |
2 |
John |
2 |
Bill |
2 |
Joe |
3 |
Joe |
3 |
Bill |
3 |
John |
3 |
Mick |
3 |
Joe |