简体   繁体   English

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

[英]sql server 2008, cannot use order by in subquery

here's my sql server 2008 stored procedure. 这是我的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

in my code, you will see I comment out the order by 在我的代码中,你会看到我通过注释掉订单

 -- ORDER BY  S.CreatedDate DESC

because order by will not work in subquery. 因为order by不会在子查询中起作用。 i need to show the lastest one on the top. 我需要在最顶层展示最新的一个。 is there a way I can use order by in my code? 有没有办法在我的代码中使用order by?

That's right. 那就对了。 It is not allowed, because it will do nothing. 这是不允许的,因为它什么都不做。

Having the latest one at the top in the subquery will do nothing to the result set using the subquery. 拥有最新的一个在子查询前不会做任何事情的结果使用子查询设置。

Add the needed column to the result set ORDER BY : 将所需列添加到结果集ORDER BY

ORDER BY seq.CreatedDate DESC, seq.rownum

Or: 要么:

ORDER BY seq.rownum, seq.CreatedDate DESC

您可以在Row_NUMBER()添加S.CreatedDate

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM