3

这是我的 sql server 2008 存储过程。

ALTER PROCEDURE [dbo].[GetSharedSmoothies]
    @Page INT ,
    @Status INT ,
    @ItemPerPage INT
AS 
    BEGIN
        SET NOCOUNT ON;

        DECLARE @X INT 
        DECLARE @Y INT

        SET @X = ( @Page - 1 ) * @ItemPerPage
        SET @Y = @Page * @ItemPerPage


        SELECT  *
        FROM    ( SELECT    S.* ,
                            U.Avatar ,
                            U.Displayname ,
                            ( SELECT    COUNT(Id)
                              FROM      Vote
                              WHERE     Vote.SmoothieId = S.Id
                            ) AS Votes ,
                            ROW_NUMBER() OVER ( ORDER BY S.Id ) rownum
                  FROM      dbo.Smoothie AS S
                            INNER JOIN dbo.[User] AS U ON S.UserId = U.Id
                  WHERE     S.IsPublic = 1
                            AND S.Status = 3
                            AND S.UserId > 0
                  -- ORDER BY  S.CreatedDate DESC
                ) seq
        WHERE   seq.rownum BETWEEN @X AND @Y
        ORDER BY seq.rownum
    END

在我的代码中,你会看到我注释掉了订单

 -- ORDER BY  S.CreatedDate DESC

因为 order by 在子查询中不起作用。我需要在顶部显示最新的。有没有办法可以在我的代码中使用 order by?

4

2 回答 2

3

这是正确的。这是不允许的,因为它不会做任何事情。

将最新的放在子查询的顶部不会对使用子查询的结果集做任何事情。

将所需的列添加到结果集中ORDER BY

ORDER BY seq.CreatedDate DESC, seq.rownum

或者:

ORDER BY seq.rownum, seq.CreatedDate DESC
于 2012-12-31T17:05:43.920 回答
3

您可以S.CreatedDateRow_NUMBER()

ROW_NUMBER() OVER (PARTITION BY S.Id ORDER BY S.CreatedDate DESC) AS RowNum

于 2012-12-31T17:07:56.243 回答