T-SQL How to select only Second row from a table?

前端 未结 15 1363
攒了一身酷
攒了一身酷 2020-12-28 12:31

I have a table and I need to retrieve the ID of the Second row. How to achieve that ?

By Top 2 I select the two first rows, but I need only

15条回答
  •  一个人的身影
    2020-12-28 13:02

    Certainly TOP will surfice if you simply want the TOP 2, but if you need them individually so that you can do something with those values then use the ROW_NUMBER which will give you more control over the rows you want to select

    ps. I did this as i'm not sure if the OP is after a simple TOP 2 in a select. (I may be wrong!)

    -- Get first row, same as TOP 1
    SELECT [Id] FROM 
    (
        SELECT [Id], ROW_NUMBER() OVER (ORDER BY [Id]) AS Rownumber
        FROM table
    ) results
    WHERE results.Rownumber = 1
    
    -- Get second row only
    SELECT [Id] FROM 
    (
        SELECT [Id], ROW_NUMBER() OVER (ORDER BY [Id]) AS Rownumber
        FROM table
    ) results
    WHERE results.Rownumber = 2
    

提交回复
热议问题