Return row of every n'th record

前端 未结 3 630
梦谈多话
梦谈多话 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:40
    Select B.name 
    from (Select row_number() over (order by ordering) as row_num, 
          A.name 
          from (Select name,'P1' as ordering 
                from [dbo].[every_2nd_record]
               ) A
          ) B
    where B.row_num%2=0
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-12-16 09:48

    You don't have to use row number, any integer field will do. On most tables we have an autonumber field. For simplicity, I will call it ID. To display every 13th record:

    Select ID, LastName, FirstName FROM Users WHERE ID%13 = 0 ORDER BY ID
    
    0 讨论(0)
提交回复
热议问题