Stormshadow
Stormshadow

Reputation: 7179

SQL: Finding user with most number of comments

I need to find out the user who has posted the most number of comments. There are two tables 1)users(Id, DisplayName) 2)comments(Id, UserId, test) . I have used the following query

Select DisplayName from users INNER JOIN (Select UserId, max(comment_count) as `max_comments from (Select UserId, count(Id) as comment_count from comments group by UserId) as` T1) as T2 ON users.Id=T2.UserId

However, this returns to me the Display Name of the user with Id = 1 rather than what I want. How do I work around this ?

Upvotes: 0

Views: 2430

Answers (1)

Meff
Meff

Reputation: 5999

SELECT TOP 1
 U.DisplayName,
 COUNT(C.ID) AS CommentCount
FROM
 Users AS U
 INNER JOIN Comments AS C ON U.ID = C.UserID
GROUP BY
 U.DisplayName
ORDER BY
 COUNT(C.ID) DESC

Upvotes: 1

Related Questions