Oracle: I need to select n rows from every k rows of a table

倾然丶 夕夏残阳落幕 提交于 2020-01-17 06:10:14

问题


For example: My table has 10000 rows. First I will divide it in 5 sets of 2000(k) rows. Then from each set of 2000 rows I will select only top 100(n) rows. With this approach I am trying to scan some rows of table with a specific pattern.


回答1:


Assuming you are ordering them 1 - 10000 using some logic and want to output only rows 1-100,2001-2100,4001-4100,etc then you can use the ROWNUM pseudocolumn:

SELECT *
FROM   (
  SELECT t.*,
         ROWNUM AS rn            -- Secondly, assign a row number to the ordered rows
  FROM   (
    SELECT *
    FROM   your_table
    ORDER BY your_condition      -- First, order the data
  ) t
)
WHERE MOD( rn - 1, 2000 ) < 100; -- Finally, filter the top 100 per 2000.

Or you could use the ROW_NUMBER() analytic function:

SELECT *
FROM   (
  SELECT t.*,
         ROW_NUMBER() OVER ( ORDER BY your_condition ) AS rn
  FROM   your_table
)
WHERE  MOD( rn - 1, 2000 ) < 100;

Is it possible to increase the set of sample data exponentially. Like 1k, 2k, 4k,8k....and then fetch some rows from these.

Replace the WHERE clause with:

WHERE rn - POWER(
             2,
             TRUNC( CAST( LOG( 2, CEIL( rn / 1000 ) ) AS NUMBER(20,4) ) )
           ) * 1000 + 1000 <= 100



回答2:


This solution uses the analytic ntile() to split the raw data into five buckets. That result set is labelled using the analytic row_number() which provides a filter to produce the final set:

with sq1 as ( select id, col1, ntile(5) over (order by id asc) as quintile
              from t23
            )
    , sq2 as (  select id, col1, quintile
                      , row_number() over ( partition by quintile order by id asc) as rn
                from sq1 )
select *
from sq2
where rn <= 200
order by quintile, rn
/



回答3:


use partition by and order by with row_number. it will look like following:

row_number()over(partition by partition_column order by order_column)<=100

partition_column will be your condition to divide set. order_column will be your condition to select top 100.



来源:https://stackoverflow.com/questions/43885367/oracle-i-need-to-select-n-rows-from-every-k-rows-of-a-table

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!