2013-12-19 83 views
0

我目前得到的錯誤:SQL服務器:不能對包含聚合或子查詢的表達式執行聚合函數

Cannot perform an aggregate function on an expression containing an aggregate or a subquery

完整的查詢:

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, " + 

我試圖用教程自己修復它,但不幸的是我得到v其他錯誤。我仍然是一個初學者,所以我沒有很多關於SQL的知識。不幸的是,如果有人能幫助我,我會非常感激!

在此先感謝。

+1

不連接查詢。這讓您容易受到SQL注入的影響。 – Szymon

回答

1

問題在於你的子查詢。讀取/修改以長串字符串連接呈現的查詢是非常困難的。只是在問題中顯示查詢會更好。

考慮這個子查詢:

(Select Count(*) From Votes where WebsiteID = Websites.Id) as TotalVotes 

的問題是,Websites.Id沒有得到很好的外部查詢定義。你有三個選擇。首先,你可以把它改成:

(Select Count(*) From Votes where WebsiteID = max(Websites.Id)) as TotalVotes 

或者,您可以包括group by子句中Websites.Id

或者,您實際上可以在group by的字段中執行比較邏輯。

相關問題