title: SQL Server : cannot perform an aggregate function on an expression containing an aggregate or a subquery
body: <p>I'm currently getting the error: </p>
  
  <blockquote>
    <p>Cannot perform an aggregate function on an expression containing an aggregate or a subquery</p>
  </blockquote>
  
  <p>The full query:</p>
  
  <pre><code>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 &gt; " + number + " And RowNum &lt;= " + amount + " " +
  "Order by TotalVotes ";
  </code></pre>
  
  <p>The line causing the problem is:</p>
  
  <pre><code>" AVG(ISNULL((Select Rating From WebsiteRating where WebsiteID = Websites.Id), 5)) as Rating, " +
  </code></pre>
  
  <p>I tried to fix it myself with tutorials, but unfortunately I was getting various other errors. I'm still a beginner, so I don't have a lot of knowledge about SQL unfortunately..</p>
  
  <p>If anyone could help me out, i would be very thankful!</p>
  
  <p>Thanks in advance.</p>