有人可以帮我纠正这个SQL 08查询吗?

时间:2009-09-22 11:25:11

标签: sql-server sql-server-2008

当我运行下面的SQL 08查询时,我得到一个错误,即tbrm_Article.ArticleID无效,因为它不包含在聚合函数或GROUP BY子句中。

我知道问题与以下方面有关:     AVG(tbrm_Votes.True)AS真相,     AVG(tbrm_Votes.False)AS False, 以及后续加入tbrm_Votes表。

tbrm_votes表包含文章ID,真数列,假数列。我试图平均给定文章ID的所有真假数字。文章ID可以在投票表中多次出现。

SELECT * FROM

(

SELECT
tbrm_Article.ArticleID, 
tbrm_Article.CountryID,
tbrm_Article.CategoryID,
tbrm_Article.Title,
tbrm_Article.ArticleDetail,
tbrm_Article.Source,
tbrm_Article.ArticleDateTimeAdded,
tbrm_Article.ViewCount,
tbrm_Article.CommentCount,
tbrm_CountryList.CountryName AS CountryName,
tbrm_CountryList.CountryImage AS CountryImage,
tbrm_CategoryList.CategoryName AS CategoryName,
tbrm_CategoryList.CategoryImage AS CategoryImage,
aspnet_Users.UserName AS UserName,
AVG(tbrm_Votes.True) AS Truth,
AVG(tbrm_Votes.False) AS False,
ROW_NUMBER() OVER (ORDER BY tbrm_Article.ArticleDateTimeAdded DESC) AS RowRank

FROM

tbrm_Article INNER JOIN
tbrm_CountryList ON tbrm_Article.CountryID = tbrm_CountryList.CountryID INNER JOIN
tbrm_CategoryList ON tbrm_Article.CategoryID = tbrm_CategoryList.CategoryID INNER JOIN
    aspnet_Users ON tbrm_Article.UserID = aspnet_Users.UserID INNER JOIN
    tbrm_Votes ON tbrm_Article.ArticleID = tbrm_Votes.ArticleID



)  Article
WHERE Article.RowRank > @PageIndex AND RowRank <= (@PageIndex + @PageSize)
ORDER BY Article.ArticleDateTimeAdded DESC

如果有人能告诉我哪里出错了,我会很感激。感谢

2 个答案:

答案 0 :(得分:3)

如果您有平均或其他聚合函数,则需要说出其他字段的组合方式。

即计算平均值的行数。

这是由group by命令完成的。这表示取这些字段并对这些字段中具有相同值的行进行汇总。 (Sybase文档说'group by通常与聚合一起使用,以指定如何对选择查询的未聚合列进行分组。')

因此,我们需要

group by
  tbrm_Article.ArticleID, 
  tbrm_Article.CountryID,
  tbrm_Article.CategoryID,
  tbrm_Article.Title,
  tbrm_Article.ArticleDetail,
  tbrm_Article.Source,
  tbrm_Article.ArticleDateTimeAdded,
  tbrm_Article.ViewCount,
  tbrm_Article.CommentCount,
  tbrm_CountryList.CountryName 
  tbrm_CountryList.CountryImage 
  tbrm_CategoryList.CategoryName 
  tbrm_CategoryList.CategoryImage 
  aspnet_Users.UserName AS UserName

答案 1 :(得分:0)

使用分析替换聚合:

AVG(tbrm_Votes.True) OVER() AS Truth
AVG(tbrm_Votes.False) OVER() AS False