This is often the case. I need to add a column of numbers similar to identity in the query results. Although it is not difficult to implement it in client programming, sometimes I want to retain the existing class, if you do not want to perform additional coding on the client side, you have to find a solution in SQL.
First, we will introduce a method to complete with an SQL statement. The principle is to query the number of records greater than or equal to this record in the result to obtain its rank.
Example:
Use pubs
Select count (*) as rank, a1.au _ lname, a1.au _ fname
From authors A1, authors A2
Where a1.au _ lname + a1.au _ fname> = a2.au _ lname + a2.au _ fname
Group by a1.au _ lname, a1.au _ fname
Order by rank
However, this method has its own limitations. The first is poor performance, and the second is that if the same record exists, rank will be tied. For example, if there are two 2, but no more than 3
Is there any other way? Of course, SQL provides an identity function to obtain the value of the ID column. Unfortunately, this function can only be used in select into statements, so we have to introduce a temporary table.
Example:
Use pubs
Select Identity (INT, 1, 1) As rank, au_lname, au_fname
Into # TMP
From authors
Select * from # TMP
Drop table # TMP
The performance and applicability of this method are better than those of the first method, but the disadvantage is that several SQL statements must be used to complete the process.
If possible, we recommend that you complete this operation on the client.