views:

26

answers:

3

What's the best way to do something like this in T-SQL?

SELECT DISTINCT ID
FROM Members,
INNER JOIN Comments ON Members.MemberId = Comments.MemberId
WHERE COUNT(Comments.CommentId) > 100

Trying to get the members who have commented more than 100 times. This is obviously invalid code but what's the best way to write this?

+6  A: 

This should get you what you're after. I'm not saying this is the absolutely best way of doing it, but it's unlikely you'll find anything better.

SELECT ID
FROM   Members
INNER JOIN Comments
ON Members.MemberId = Comments.MemberId
GROUP BY ID
HAVING COUNT(*) > 100
Will A
+1  A: 

I like using a subquery.

SELECT DISTINCT m.ID
FROM Members m
WHERE (SELECT COUNT(c.CommentID)
       FROM Comments c
       WHERE c.MemberID = m.MemberID) > 100
Dustin Laine
+1  A: 

Try

SELECT ID
FROM Members
INNER JOIN (SELECT MemberID FROM Comments 
     GROUP BY MemberID HAVING COUNT(CommentId) > 100) 
AS CommentCount ON Members.MemberID = CommentCount.CommentID
LittleBobbyTables
HAVING must follow GROUP BY...
Will A
I always get that wrong, thanks
LittleBobbyTables
Me too. I also like putting `WHERE` after `GROUP BY`. :)
Will A