SQL CTE and ORDER BY affecting result set

后端 未结 2 690
忘掉有多难
忘掉有多难 2021-01-12 04:11

I\'ve pasted a very simplified version of my SQL query below. The problem that I\'m running into is that the ORDER BY statement is affecting the select results

相关标签:
2条回答
  • 2021-01-12 05:08

    I think you can add new column like

    SELECT ROW_NUMBER() OVER(ORDER BY <ColumnName>;) AS RowNo
    

    and then all your columns.. this would help you to query using the CTE anchor... using between, where etc clauses..

    0 讨论(0)
  • 2021-01-12 05:14

    When you use SELECT TOP n you must supply an ORDER BY if you want deterministic behaviour otherwise the server is free to return any 10 rows it feels like. The behaviour you are seeing is perfectly valid.

    To solve the problem, specify an ORDER BY inside the CTE:

    WITH results AS
    (
        SELECT TOP 10 ID, Date
        FROM dbo.items
        ORDER BY ID DESC 
    )
    SELECT ID
    FROM results
    ORDER BY Date
    
    0 讨论(0)
提交回复
热议问题