Oracle:需要以指数方式获取行

时间:2017-05-10 10:31:05

标签: sql oracle

我从另一篇帖子中得到以下查询,该帖子从每2000行中选择100行。 像这样:1-100,2001-2100,4001-4100,6001-6100,8001-8100等。

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

现在我想以指数方式选择我的数据。这样它将从前1000行中选择100行,然后从接下来的2000行中选择,然后从接下来的4000行中选择。 像这样:1-100,2000-2100,4000-4100,8000-8100,16000-16100等。 我们的想法是扫描具有特定模式的行。

3 个答案:

答案 0 :(得分:0)

根据您的描述,您可以使用日志来定义组。这可能与你想要的足够接近:

select t.*
from (select t.*,
             row_number() over (floor(log(2, floor(1 + (seqnum - 1) / 1000) ))
                                order by col
                               ) as seqnum_2
      from (select t.*, row_number() over (order by col) as seqnum
            from t
           ) t
where seqnum_2 <= 100;

与您的描述不同的是,第一组是1-999,1000-1999,依此类推。

答案 1 :(得分:0)

您可以使用power函数和简单的分层查询,然后将其与您的表连接。以下是all_objects视图的示例:

with rng as (select 0 num from dual union all
             select 1000 * power(2, level) from dual connect by level < 10 )
select * 
  from (select row_number() over (order by object_name) rn, object_name from all_objects)
  join rng on rn between num + 1 and num + 100 

答案 2 :(得分:0)

你在对your previous question的评论中问了这个问题,我在那里回答了......

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 rn - POWER(                -- Finally, filter the top 100.
             2,
             TRUNC( CAST( LOG( 2, CEIL( rn / 1000 ) ) AS NUMBER(20,4) ) )
           ) * 1000 + 1000 <= 100

这将占用1-1000,1001-3000,3001-7000,7001-1000等组的前100行

或者,获取行:

  

1-100,2000-2100,4000-4100,8000-8100,16000-16100,32000-32100等。

然后:

WHERE CASE                -- Finally, filter the top 100.
        WHEN rn <= 2000 THEN rn
        ELSE rn - POWER(
                    2,
                    TRUNC( CAST( LOG( 2, CEIL( rn / 1000 - 1 ) ) AS NUMBER(20,4) ) )
                  ) * 1000
      END <= 100