I have 3 tables:
[Users]: UserId, Name...[Topics]: TopicId, CreatorUserId...[Comments]: CommentId, TopicId....
Now, I’d like to select the creators of the most popular topics according to this mechanism:
get the comments, which is newer than the specified date. Group those comments by the creator of the topic, and order by the number of rows in the groups.
However, I’m not sure that my query follows this logic(it seems according to the results, but I have only a few users and topics), but the main problem is that when I want to select the name of the user (Users.Name), I get an error:
Column ‘[TestDatabase].[dbo].[Users].[Name]’ is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
T-SQL query:
SELECT
Users.UserId, Users.Name, COUNT(Users.UserId) as RowCountInGroup
FROM [TestDatabase].[dbo].[Users]
INNER JOIN [TestDatabase].[dbo].[Topics] ON Topics.CreatorUserId = Users.UserId
INNER JOIN [TestDatabase].[dbo].[Comments] ON Comments.TopicId = Topics.TopicId
WHERE
Comments.CreationDate > CAST('14 SEPTEMBER 2012' as DateTime)
GROUP BY Users.UserId
ORDER BY RowCountInGroup DESC
Thanks for helping me.
EDIT: I’ve copied the original error message. I need to select the Email, the City, etc columns from the User, so I’m not sure that adding all of these to the group by clause is the best solution.
You need to group by both columns (or in general: all columns) that you select (that are not aggregated by the
COUNTaggregate operator):