Oracle:我需要从 table 的每 k 行中 select n 行

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

例如: 我的 table 有 10000 行。首先,我将把它分成 5 组,每组 2000(k) 行。然后从每组 2000 行中我将 select 仅前 100(n) 行。 通过这种方法,我尝试使用特定模式扫描 table 的某些行。

使用分区依据和排序依据row_number。它将如下所示:

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

partition_column 将是您划分集合的条件。 order_column 将是您进入 select 前 100 名的条件。

此解决方案使用解析 ntile() 将原始数据拆分为五个桶。该结果集使用解析 row_number() 进行标记,它提供了一个过滤器来生成最终结果集:

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
/

假设您使用某种逻辑对它们进行排序 1 - 10000 并且只想输出行 1-100,2001-2100,4001-4100,etc 那么您可以使用 ROWNUM 伪列:

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.

或者您可以使用 ROW_NUMBER() 分析函数:

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.

WHERE 子句替换为:

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