根据oracle中的计数在oracle中生成随机数(非重复整数)

u91tlkcl  于 2023-10-16  发布在  Oracle
关注(0)|答案(1)|浏览(182)

看看我是否可以根据总计数生成一个非重复随机整数-例如下面的代码-

with all_val as (    
select 1 as ID, 'A' as val from dual  union all 
select 2 as ID, 'A' as val from dual  union all 
select 3 as ID, 'A' as val from dual  union all  
select 4 as ID, 'B' as val from dual  union all 
select 5 as ID, 'B' as val from dual  union all  
select 6 as ID, 'B' as val from dual  union all 
select 7 as ID, 'A' as val from dual  union all 
select 8 as ID, 'A' as val from dual  union all 
select 9 as ID, 'A' as val from dual)

select A.*,
(DBMS_RANDOM.VALUE( 0, X?? )) as RND from (
select B.* from all_val B
where VAL <> 'B') A;

ID的1-3和7-9将被选中,但生成的随机数只能是1-6。
希望这有意义。
Tia

blmhpbnm

blmhpbnm1#

如果你想让随机数的范围从1到查询返回的行数,你可以通过传递count(*) over ()作为dbms_random.value的上限来得到这个值:

with all_val as (    
  select 1 as ID, 'A' as val from dual  union all 
  select 2 as ID, 'A' as val from dual  union all 
  select 3 as ID, 'A' as val from dual  union all  
  select 4 as ID, 'B' as val from dual  union all 
  select 5 as ID, 'B' as val from dual  union all  
  select 6 as ID, 'B' as val from dual  union all 
  select 7 as ID, 'A' as val from dual  union all 
  select 8 as ID, 'A' as val from dual  union all 
  select 9 as ID, 'A' as val from dual
)

select
  a.*,
  round ( dbms_random.value ( 1, count (*) over () ) ) as rnd
from(
  select b.*
  from   all_val b
  where  val <> 'B'
) a;

ID    VAL    RND    
    1 A           1 
    2 A           2 
    3 A           6 
    7 A           5 
    8 A           6 
    9 A           3

相关问题