无法从数据库中选择列

时间:2012-10-03 18:50:19

标签: sql sql-server-2008

我有3张桌子:

  • [Users]: UserId, Name...
  • [Topics]: TopicId, CreatorUserId...
  • [Comments]: CommentId, TopicId...

现在,我想根据这个机制选择最受欢迎主题的创建者: 获取比指定日期更新的注释。由主题的创建者对这些注释进行分组,并按组中的行数排序。

但是,我不确定我的查询是否遵循这个逻辑(似乎根据结果,但我只有少数用户和主题),但主要问题是当我想选择名称时用户(Users.Name),我收到错误:

  

列'[TestDatabase]。[dbo]。[Users]。[Name]'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。

T-SQL查询:

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

感谢您的帮助。

编辑:我复制了原始错误消息。我需要从用户中选择电子邮件,城市等列,因此我不确定将所有这些列添加到group by子句是最佳解决方案。

3 个答案:

答案 0 :(得分:4)

您需要按您选择的两个列(或通常:所有列)进行分组(未由COUNT聚合运算符聚合):

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, Users.Name   <=== you need to add "Users.Name" here!
ORDER BY RowCountInGroup DESC

答案 1 :(得分:1)

您需要在group by子句

中同时拥有UserId和Name

答案 2 :(得分:0)

这是实现目标的一种方式:

SELECT a.UserId, b.Name, a.RowCountInGroup
FROM
    (SELECT Users.UserId, 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) a
LEFT JOIN [TestDatabase].[dbo].[Users] b ON b.UserId = a.UserId

如果您包含带有汇总的列,则必须GROUP BY该列:

SELECT col1, col2, COUNT(col3)
FROM table
GROUP BY col1, col2