根据oracle表中的值创建偶数范围

时间:2018-04-15 05:04:24

标签: plsql oracle11g partition

我有一个100k行的大表,PRIMARY KEY的数据类型为NUMBER。在此列中填充数据的方式是使用随机数生成器。

所以我的问题是,是否有可能有一个SQL查询可以帮助我使用值范围均匀地对表进行分区。例如:如果我的列值是这样的:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10

我希望将其拆分为三个分区,然后我希望输出如下:

Range 1          1-3
Range 2          4-7
Range 3          8-10

2 个答案:

答案 0 :(得分:0)

听起来你想要WIDTH_BUCKET()功能。 Find out more.

此查询将根据id为您提供分为20个存储桶的1250行表的开始和结束范围:

with bkt as (
    select id
           , width_bucket(id, 1, 1251, 20) as id_bucket
    from t23
)
select id_bucket
       , min(id) as bkt_start
       , max(id) as bkt_end
       , count(*)
from bkt
group by id_bucket
order by 1
;

两个中间参数指定最小值和最大值;最后一个参数指定存储桶的数量。输出是最小和最大弓之间的行尽可能均匀地分成指定数量的桶。小心最小和最大参数;我发现选择不当的界限会对分裂产生奇怪的影响。

答案 1 :(得分:0)

此解决方案无法使用width_bucket功能。虽然它更冗长,效率肯定更低,但它会尽可能均匀地分割数据,即使缺少某些ID值。

CREATE TABLE t AS
 SELECT rownum AS id
   FROM dual 
CONNECT BY level <= 10;

WITH
   data AS (
      SELECT id, rownum as row_num
        FROM t
   ),
   total AS (
      SELECT count(*) AS total_rows
        FROM data
   ),
   parts AS (
      SELECT rownum as part_no, total.total_rows, total.total_rows / 3 as part_rows
        FROM dual, total 
     CONNECT BY level <= 3
   ),
   bounds AS (
      SELECT parts.part_no, 
             parts.total_rows, 
             parts.part_rows, 
             COALESCE(LAG(data.row_num) OVER (ORDER BY parts.part_no) + 1, 1) AS start_row_num,
             data.row_num AS end_row_num
       FROM data
       JOIN parts 
         ON data.row_num = ROUND(parts.part_no * parts.part_rows, 0)
   )
SELECT bounds.part_no, d1.ID AS start_id, d2.ID AS end_id
  FROM bounds
  JOIN data d1
    ON d1.row_num = bounds.start_row_num
  JOIN data d2
    ON d2.row_num = bounds.end_row_num
ORDER BY bounds.part_no;

   PART_NO   START_ID     END_ID
---------- ---------- ----------
         1          1          3
         2          4          7
         3          8         10