Select every Nth row from a table

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • plzansmyquery
    New Member
    • Mar 2008
    • 4

    Select every Nth row from a table

    Hi all,

    please help me in writing a query for selecting every Nth row in a table.

    Thank you in advance
  • amitpatel66
    Recognized Expert Top Contributor
    • Mar 2007
    • 2358

    #2
    Originally posted by plzansmyquery
    Hi all,

    please help me in writing a query for selecting every Nth row in a table.

    Thank you in advance
    Could you please post your table structure here and what you have tried so far?

    Comment

    • deepuv04
      Recognized Expert New Member
      • Nov 2007
      • 227

      #3
      Originally posted by amitpatel66
      Could you please post your table structure here and what you have tried so far?
      Hi,
      try the following query to get nth record
      [code=sql]

      SELECT * From (SELECT *,(Dense_Rank() Over (Order By Column_Name Desc)) As Rank
      From Table_Name) As Z Where Rank=3

      [/code]

      Comment

      • plzansmyquery
        New Member
        • Mar 2008
        • 4

        #4
        Hello deepuv04

        Thank you for the reply. But this query gives only the nth record in table, but I want every Nth row (ex: 10th, 20th, 30th....) in the table. Can we do that?

        Comment

        • deepuv04
          Recognized Expert New Member
          • Nov 2007
          • 227

          #5
          Originally posted by plzansmyquery
          Hello deepuv04

          Thank you for the reply. But this query gives only the nth record in table, but I want every Nth row (ex: 10th, 20th, 30th....) in the table. Can we do that?
          hi,
          we can do that. pass the ranks as varchar comma seperated

          eg: @Rank as '10,20,30'

          use the following query, it will give you the ranks you specified, if @Rank is null the will give you all the records

          [code=sql]
          SELECT * FROM (SELECT *,(Dense_Rank() Over (ORDER BY Column_Name DESC)) AS Rank
          FROM Table_Name) AS Z
          WHERE (','+isnull(@Ra nk,convert(varc har(10),Z.Rank) )+',') like
          ('%,'+convert(v archar(20),Z.Ra nk)+ ',%')))

          [/code]

          Comment

          • plzansmyquery
            New Member
            • Mar 2008
            • 4

            #6
            Thank you ..I will try this..

            Comment

            Working...