Assume I've SQL query like this:
SELECT id, name, index(not a real column) FROM users ORDER BY rating DESC
I want to add column to selected columns that will represent the index of the record.
Example:
id name rating
1 a 4
2 b 2
3 c 8
4 d 5
For this table I want to get:
id name rating index
3 c 8 1
4 d 5 2
1 a 4 3
2 b 2 4
SQL Server CREATE INDEX statement In this syntax: First, specify the name of the index after the CREATE NONCLUSTERED INDEX clause. Note that the NONCLUSTERED keyword is optional. Second, specify the table name on which you want to create the index and a list of columns of that table as the index key columns.
An important point to consider after selecting the proper columns to be involved in the index key is the order of the columns in the index key, especially when the key consists of multiple columns. Try to place the columns that are used in the query conditions first in the SQL Server index key.
Try the following to get the row_index:
set @row_num = 0;
SELECT id,name,rating, @row_num := @row_num + 1 as row_index FROM users
ORDER BY rating desc;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With