I need to add an auto generated auto-increment id to a query results.
For example, for the query
SELECT TOP 3 Users.Reputation FROM Users ORDER BY 1 DESC
Instead of getting
- 101
- 100
- 99
I want to get
- 1, 101
- 2, 100
- 3, 99
How can I do it?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
How about:
This is a CTE (Common Table Expression) available in SQL Server 2005 and newer, combined with the
ROW_NUMBER()ranking function, also available in 2005 and newer.It creates an “on-the-fly” view for just the next statement and allows to do some extra processing first, before selecting. The
ROW_NUMBER()just adds a consecutive number to each row in the order defined in theOVER (ORDER BY ....)clause. So the first row gets #1, the second #2 and so on.Read more about CTE’s here: MSDN – Using Common Table Expressions
Read more about
ROW_NUMBERand other ranking functions here: MSDN ROW_NUMBER