If this is your first visit, be sure to check out the FAQ by clicking the link above. You may have to register before you can post: click the register link above to proceed. To start viewing messages, select the forum that you want to visit from the selection below.

 
Go Back  dBforums > Database Server Software > DB2 > SQL selecting every nth row of a table

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old 08-27-04, 11:17
bon213 bon213 is offline
Registered User
 
Join Date: Jan 2004
Posts: 5
SQL selecting every nth row of a table

Is it possible to write a select statement where you only retrieve every 5th row in the table?

Thanks in advance
Reply With Quote
  #2 (permalink)  
Old 08-27-04, 11:58
Damian Ibbotson Damian Ibbotson is offline
Padawan
 
Join Date: Jun 2002
Location: UK
Posts: 525
If you have OLAP functionality, use...
Code:
select col1, col2 ...
from (select col1, row_number()over() rn
      from yourTable) aTempTable
where mod(rn,5) = 0
;
If you don't have OLAP functionality, use...
Code:
select col1, col2 ...
from (select a.col1, a.col2 ... , count(*) rn
       from yourTable a
       ,    yourTable b
       where a.aUniqueIndexCol >= b.aUniqueIndexCol
       group by a.col1, a.col2 ...
     ) aTempTable
where mod(rn,5) = 0
;
The second example would involve a slightly more complicated join if your table has a composite unique key (and if your table has no unique identifier, you're outta luck!)

Damian
Reply With Quote
Reply

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On