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

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

    Use ROW_NUMBER() to number the rows, but use TOP to only process the first two.

    try this:

    DECLARE @YourTable table (YourColumn int)
    INSERT @YourTable VALUES (5)
    INSERT @YourTable VALUES (7)
    INSERT @YourTable VALUES (9)
    INSERT @YourTable VALUES (17)
    INSERT @YourTable VALUES (25)
    
    ;WITH YourCTE AS
    (
      SELECT TOP 2
        *, ROW_NUMBER() OVER(ORDER BY YourColumn) AS RowNumber
      FROM @YourTable
    ) 
    SELECT *
    FROM YourCTE
    WHERE RowNumber=2
    

    OUTPUT:

    YourColumn  RowNumber
    ----------- --------------------
    7           2
    
    (1 row(s) affected)
    

提交回复
热议问题