我有一个需要订购的查询,然后我需要从中选择特定的行。
错误:
附加信息:ORDER BY子句在视图,内联函数,派生表,子查询和公用表表达式中无效,除非还指定了TOP,OFFSET或FOR XML。
我要做的是以下内容:
"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行中的0行。
我还是sql的初学者,总是和Linq一起工作。但这是我的一个旧项目,仍然适用于普通的SQL。
答案 0 :(得分: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子句之后出现的所选行应用订单。
答案 1 :(得分:0)
评论ORDER BY网站.Id DESC。 &安培;在
中使用desc这个命令 RowNum = ROW_NUMBER() OVER (ORDER BY Websites.ID Desc)
OR 在子查询中使用它。(没有对此行进行评论)
SELECT top 100 percent