2014-09-27 57 views
0

我有一個需要排序的查詢,然後我需要從中選擇特定的行。無法在查詢中訂購

錯誤:

Additional information: The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP, OFFSET or FOR XML is also specified.

我所試圖做的是以下幾點:

"SELECT * FROM (SELECT" + 
         " Websites.Id as websiteId, " + 
         " Websites.Title, " + 
         " Websites.Description, " + 
         " Websites.Url, " + 
         " Websites.BannerURL, " + 
         " (Select Count(*) From Votes where WebsiteID = Websites.Id And [Unique] = 1 And Date = '" + 
         Date + "') as TotalVotes, " + 
         " ISNULL((Select AVG(rating) From WebsiteRating where WebsiteID = Websites.Id), 5) as Rating, " + 
         " Users.Username, " + 
         " (Select Count(*) From Redirects where WebsiteID = Websites.Id And [Unique] = 1 And Date = '" + 
         Date + "') as Redirects, " + 
         " RowNum = ROW_NUMBER() OVER (ORDER BY Websites.ID) " + 
         " FROM Websites " + 
         " INNER JOIN Users ON Websites.UserID = Users.Id " + 
         " Where Websites.Enabled = 1" + 
         " GROUP BY Websites.Title, Websites.Description, Websites.Url, Websites.BannerURL , Users.Username, Websites.Id" + 
         // Error 
         " ORDER BY Websites.Id DESC" + 
         ") as Table1 " + 
         "WHERE RowNum > " + number + " And RowNum <= " + amount + ""; 

當我通過後做的順序:

"WHERE RowNum > " + number + " And RowNum <= " + amount + ""; 

然後首先選擇從0到25的行,然後排序。但我想先訂購它,然後從該列表中選擇25行。

我仍然是一個初學sql,總是與Linq合作。但這是我的一箇舊的項目,仍然可以使用普通的sql。

回答

1

試試這個:

"SELECT * FROM (SELECT" + 
    " Websites.Id as websiteId, " + 
    " Websites.Title, " + 
    " Websites.Description, " + 
    " Websites.Url, " + 
    " Websites.BannerURL, " + 
    " (Select Count(*) From Votes where WebsiteID = Websites.Id And [Unique] = 1 And Date = '" + 
    Date + "') as TotalVotes, " + 
    " ISNULL((Select AVG(rating) From WebsiteRating where WebsiteID = Websites.Id), 5) as Rating, " + 
    " Users.Username, " + 
    " (Select Count(*) From Redirects where WebsiteID = Websites.Id And [Unique] = 1 And Date = '" + 
    Date + "') as Redirects, " + 
    " RowNum = ROW_NUMBER() OVER (ORDER BY Websites.ID) " + 
    " FROM Websites " + 
    " INNER JOIN Users ON Websites.UserID = Users.Id " + 
    " Where Websites.Enabled = 1" + 
    " GROUP BY Websites.Title, Websites.Description, Websites.Url, Websites.BannerURL , Users.Username, Websites.Id" + 
    ") as Table1 " + 
    " WHERE RowNum > " + number + " And RowNum <= " + amount + "" + 
    " ORDER BY RowNum DESC" 
    ; 

你已經已經訂購了通過RowNum準備的數據,因此您不需要在子查詢中使用TOP或ORDER,只需將命令應用於所選行這發生在最後的where子句之後。

+0

謝謝,如果我想按子查詢命令:TotalVotes? – Jamie 2014-09-27 10:44:55

+0

您可以在子查詢完成後使用我介紹的where子句位置按任意列進行排序。但是,記住你的行選擇是基於特定的順序,所以如果你改變了演示順序,你還需要改變RowNum的計算方式。 – 2014-09-27 12:50:38

0

註釋掉ORDER BY Websites.Id DESC。 。 &使用ORDER BY DESC這個在

RowNum = ROW_NUMBER() OVER (ORDER BY Websites.ID Desc) 

OR 使用此子查詢中(上面這一行沒有評論)

SELECT top 100 percent