SQL: Numbering the rows returned by a SELECT statement

前端 未结 6 2193
说谎
说谎 2021-01-06 06:26

Suppose I have a SELECT statement that returns some set of results. Is there some way I can number my results in the following way:

SELECT TOP 3 Name FR

6条回答
  •  时光取名叫无心
    2021-01-06 06:54

    You could also do it with a temp table:

    SELECT TOP 3 Name FROM PuppyNames ORDER BY NumberOfVotes DESC
    

    becomes

    CREATE TABLE #RowNumberTable (
        RowNumber int IDENTITY (1,1),
        PuppyName varchar(MAX)
    )
    INSERT #RowNumberTable (PuppyName)
    SELECT TOP 3 Name FROM PuppyNames ORDER BY NumberOfVotes DESC
    SELECT * from #RowNumberTable ORDER BY RowNumber
    DROP TABLE #RowNumberTable
    

    If you'll notice, your SELECT statement is in there. It is just surrounded by stuff that makes the row numbers work.

提交回复
热议问题