Return row of every n'th record

前端 未结 3 633
梦谈多话
梦谈多话 2020-12-16 09:12

How can I return every nth record from a sub query based on a numerical parameter that I supply?

For example, I may have the following query:



        
3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-16 09:42

    This is where ROW_NUMBER can help. It requires an order-by clause but this is okay because an order-by is present (and required to guarantee a particular order).

    SELECT t.id, t.key
    FROM
    (
        SELECT id, key, ROW_NUMBER() OVER (ORDER BY key) AS rownum
        FROM datatable
    ) AS t
    WHERE t.rownum % 30 = 0    -- or % 40 etc
    ORDER BY t.key
    

提交回复
热议问题