How to select the nth row in a SQL database table?

后端 未结 30 2589
执笔经年
执笔经年 2020-11-22 06:06

I\'m interested in learning some (ideally) database agnostic ways of selecting the nth row from a database table. It would also be interesting to see how this can b

30条回答
  •  醉酒成梦
    2020-11-22 06:44

    I'm a bit late to the party here but I have done this without the need for windowing or using

    WHERE x IN (...)
    
    SELECT TOP 1
    --select the value needed from in t1
    [col2]
    FROM
    (
       SELECT TOP 2 --the Nth row, alter this to taste
       UE2.[col1],
       UE2.[col2],
       UE2.[date],
       UE2.[time],
       UE2.[UID]
       FROM
       [table1] AS UE2
       WHERE
       UE2.[col1] = ID --this is a subquery 
       AND
       UE2.[col2] IS NOT NULL
       ORDER BY
       UE2.[date] DESC, UE2.[time] DESC --sorting by date and time newest first
    ) AS t1
    ORDER BY t1.[date] ASC, t1.[time] ASC --this reverses the order of the sort in t1
    

    It seems to work fairly fast although to be fair I only have around 500 rows of data

    This works in MSSQL

提交回复
热议问题