4

I have written the following SQL code to run on my SQL Server.

SELECT 
   atd.DeviceID, 
   ROW_NUMBER() over(order by atd.deviceid) as rownumber
FROM 
   dbo.Devices atd  
WHERE 
  (rownumber between 11 and 20);

I get the following output:

Msg 207, Level 16, State 1, Line 5
Invalid column name 'rownumber'.
Msg 207, Level 16, State 1, Line 5
Invalid column name 'rownumber'.

As you can see, I want to use ROW_NUMBER to get only a subset of the rows that would normally be returned by a query. I've never used the ROW_NUMBER function before.

What am I doing wrong?

1 Answer 1

14

You can't use the alias of your column directly, wrap it on a derived table or a CTE:

SELECT *
FROM (  SELECT DeviceID, 
        ROW_NUMBER() over(order by deviceid) as rownumber
        FROM dbo.Devices) atd 
WHERE (rownumber between 11 and 20);

Or

;WITH CTE AS
(
    SELECT DeviceID, 
    ROW_NUMBER() over(order by deviceid) as rownumber
    FROM dbo.Devices
)
SELECT *
FROM CTE 
WHERE (rownumber between 11 and 20);
Sign up to request clarification or add additional context in comments.

3 Comments

Running the first query given in your answer results in the following error: The multi-part identifier "atd.DeviceID" could not be bound.
@Daniel Just take the atd prefix off the DeviceID column.
Downvoter, was the downvote only because of the prefix on the column?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.