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
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..
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