sql server 2008,不能在子查询中使用order

时间:2012-12-31 17:04:29

标签: sql sql-server-2008 stored-procedures

这是我的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?

2 个答案:

答案 0 :(得分:3)

没错。这是不允许的,因为它什么都不做。

在子查询的顶部使用最新的一个将使用子查询对结果集执行 nothing

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

ORDER BY seq.CreatedDate DESC, seq.rownum

或者:

ORDER BY seq.rownum, seq.CreatedDate DESC

答案 1 :(得分:3)

您可以在S.CreatedDate

中添加Row_NUMBER()

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