SQL基于Count排序

时间:2017-05-26 21:11:36

标签: sql-server sorting tsql count

我正在尝试通过评论滚动页面自动加载进行编辑。现在SQL查询是这样的:

ALTER PROCEDURE [dbo].[C2_Comments_Viewable] 
    @Viewable INT,
    @C2_ID BIGINT,
    @PageNo INT
AS
WITH LatestComments
AS (
    SELECT 
    ROW_NUMBER() OVER ( ORDER BY [DateAdded] ASC ) AS RowDuplicate,     
    ROW_NUMBER() OVER ( ORDER BY [DateAdded] ASC ) AS Row,
        [CommentID],
        [C2_ID],
        [Comment],
        [DateAdded],
        [Viewable]
    FROM C2_Comments
    WHERE [C2_ID] = @C2_ID
    )
SELECT 
    RowDuplicate, 
    Row, 
    CommentID, 
    [C2_ID],
    [Comment],
    [DateAdded],
    [Viewable]
FROM 
    LatestComments
WHERE 
    RowDuplicate BETWEEN (@PageNo - 1) * 100 + 1 AND @PageNo * 100
ORDER BY Row DESC

虽然这有效,但是如果返回的注释数量是<<返回值,则我会尝试将排序从DESC更改为ASC。 101。

    Case when Count < 101 Then ASC Else DESC End

似乎无法得到它。

戈登的帮助:

ALTER PROCEDURE [dbo].[C2_Comments_Viewable] 
    @Viewable INT,
    @C2_ID BIGINT,
    @PageNo INT
AS
WITH LatestComments
AS (
    SELECT 
    ROW_NUMBER() OVER ( ORDER BY [DateAdded] **DESC** ) AS RowDuplicate,     
    ROW_NUMBER() OVER ( ORDER BY [DateAdded] ASC ) AS Row,
        [CommentID],
        [C2_ID],
        [Comment],
        [DateAdded],
        [Viewable]
    FROM C2_Comments
    WHERE [C2_ID] = @C2_ID
    )
SELECT 
    RowDuplicate, 
    Row, 
    CommentID, 
    [C2_ID],
    [Comment],
    [DateAdded],
    [Viewable]
FROM 
    LatestComments
WHERE 
    RowDuplicate BETWEEN (@PageNo - 1) * 20 + 1 AND @PageNo * 20
**ORDER BY (CASE WHEN COUNT(*) OVER () < 20 THEN Row END) ASC, Row DESC**

DESCPage1 20> 6

DESCPage2 1> 5 这是我的问题,第2页是ASC

ASC

1&gt; 20 通过此订单不需要页面

有什么问题?

2 个答案:

答案 0 :(得分:0)

您可以使用两个单独的键执行此操作:

order by (case when count(*) over () < 101 then row end) ASC,
         row DESC

答案 1 :(得分:0)

我让别人帮我这个。正在使用新的@count声明和2个case语句。现在一切都在工作。

ALTER PROCEDURE [dbo].[C2_Comments_Viewable] 
    @Viewable INT,
    @C2_ID BIGINT,
    @PageNo INT
AS    
**declare @count as int
set @count = (select count(*) from  C2_Comments
    WHERE [C2_ID] = @C2_ID);**    
WITH LatestComments
AS (
    SELECT 
    ROW_NUMBER() OVER ( ORDER BY [DateAdded] DESC ) AS RowDuplicate,     
    ROW_NUMBER() OVER ( ORDER BY [DateAdded] ASC ) AS Row,
        [CommentID],
        [C2_ID],
        [Comment],
        [DateAdded],
        [Viewable]
    FROM C2_Comments
    WHERE [C2_ID] = @C2_ID
    )
SELECT 
    RowDuplicate, 
    Row, 
    CommentID, 
    [C2_ID],
    [Comment],
    [DateAdded],
    [Viewable]
FROM 
    LatestComments
WHERE 
    RowDuplicate BETWEEN (@PageNo - 1) * 100 + 1 AND @PageNo * 100
**ORDER BY CASE WHEN @count < 100 THEN Row END ASC,
        CASE WHEN @count >= 100 THEN Row END DESC**

我希望这有助于其他人!