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

前端 未结 15 1264
攒了一身酷
攒了一身酷 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:17

    Assuming SQL Server 2005+ an example of how to get just the second row (which I think you may be asking - and is the reason why top won't work for you?)

    set statistics io on
    
    ;with cte as
    (
      select *
        , ROW_NUMBER() over (order by number) as rn
      from master.dbo.spt_values
    ) 
    select *
    from cte
    where rn = 2
    
    /* Just to add in what I was running RE: Comments */
    ;with cte as
    (
      select top 2 *
        , ROW_NUMBER() over (order by number) as rn
      from master.dbo.spt_values
    ) 
    select *
    from cte
    where rn = 2
    
    0 讨论(0)
  • 2020-12-28 13:21

    This is also useful:

    SELECT t.*
    FROM (
      SELECT e1.*
        , row_number() OVER (ORDER BY e1.Rate DESC) AS _Rank
      FROM
      HumanResources.EmployeePayHistory AS e1
    ) AS t
    WHERE t._Rank = 2
    
    0 讨论(0)
  • 2020-12-28 13:24

    Select top 2 [id] from table Order by [id] desc should give you want you the latest two rows added.

    However, you will have to pay particular attention to the order by clause as that will determine the 1st and 2nd row returned.

    If the query was to be changed like this:

    Select top 2 [id] from table Order by ModifiedDate desc

    You could get two different rows. You will have to decide which column to use in your order by statement.

    0 讨论(0)
提交回复
热议问题