我目前收到错误:
无法对包含聚合或子查询的表达式执行聚合函数
完整查询:
query = "SELECT * FROM (SELECT" +
" IDWebsite = Websites.Id, " +
" Websites.Title, " +
" Websites.Description, " +
" Websites.Url, " +
" Websites.BannerURL, " +
" (Select Count(*) From Votes where WebsiteID = Websites.Id) as TotalVotes, " +
" AVG(ISNULL((Select Rating From WebsiteRating where WebsiteID = Websites.Id), 5)) as Rating, " +
" Users.Username, " +
" Websites.ID, " +
" (Select Count(*) From Redirects where WebsiteID = Websites.Id) as websiteCount, " +
" RowNum = ROW_NUMBER() OVER (ORDER BY Websites.ID) " +
" FROM Websites " +
" INNER JOIN Users ON Websites.UserID = Users.Id " +
" LEFT OUTER JOIN Votes AS Votes_1 ON Votes_1.WebsiteID = Websites.Id " +
" LEFT OUTER JOIN Redirects AS Redirects_1 ON Redirects_1.WebsiteID = Websites.Id " +
" LEFT OUTER JOIN WebsiteRating AS WebsiteRating_1 ON WebsiteRating_1.WebsiteID = Websites.Id " +
" GROUP BY Websites.Title, Websites.Description, Websites.Url, Websites.BannerURL , Users.Username, Websites.ID" +
") as Table1 " +
"WHERE RowNum > " + number + " And RowNum <= " + amount + " " +
"Order by TotalVotes ";
导致问题的一行是:
" AVG(ISNULL((Select Rating From WebsiteRating where WebsiteID = Websites.Id), 5)) as Rating, " +
我尝试用自己的教程修复它,但遗憾的是我遇到了其他各种错误。我还是初学者,所以不幸的是我没有很多关于SQL的知识......
如果有人能帮助我,我会非常感激!
提前致谢。
答案 0 :(得分:1)
问题在于你的子查询。读取/修改作为一组长串字符串连接呈现的查询非常困难。最好只在问题中显示查询。
考虑这个子查询:
(Select Count(*) From Votes where WebsiteID = Websites.Id) as TotalVotes
问题是外部查询没有很好地定义Websites.Id
。你有三个选择。首先,您可以将其更改为:
(Select Count(*) From Votes where WebsiteID = max(Websites.Id)) as TotalVotes
或者,您可以在Websites.Id
子句中加入group by
。
或者,您实际上可以对group by
。