服务器之家:专注于服务器技术及软件下载分享
分类导航

Mysql|Sql Server|Oracle|Redis|MongoDB|PostgreSQL|Sqlite|DB2|mariadb|Access|数据库技术|

服务器之家 - 数据库 - Oracle - Oracle 随机数

Oracle 随机数

2019-10-31 16:21Oracle教程网 Oracle

用于抽样统计,从数据库中按类别随机 抽取各类用户

利用oracle的dbms_random包结合rownum来实现,示例如下,随机取499户: 
select * from 
( select * from busi.t_ar_userinfo order by dbms_random.value) 
where rownum < 500; 

有关dbms_random的参考文献,链接为:http://www.psoug.org/reference/dbms_random.html 

Deprecated. Use the methods in the DBMS_CRYPTO built-in package,这个包已经不建议使用了 

附,dbms_random几个参数的介绍: 
function value return number,返回一个[0,1)之间的随机数,精度为38位(Gets a random number, greater than or equal to 0 and less than 1, with decimal 38 digits) 
function value(low IN NUMVBER,high IN NUMBER) return number,返回一个[low,high)之间的随机数 
function normal return number,return random numbers in a standard normal distribution,返回服从正态分布的一组数,标准偏差为1,期望值为0,返回值中68%介于+1 和 -1 之间,95%介于 +2 和 -2 之间,99%介于+3 和 -3之间。 
function random return BINARY_INTEGER, (Generate Random Numeric Values), 
function string(opt char,length Number) return varchar2(the maximum is 60),返回一个指定长度的字符串( Create Random Strings),opt seed values: 
'a','A'&n 

问:我工作中的问题:主管让我为了某个活动要随机取出一些符合条件的EMAIL或者手机号码用户,来颁发获奖通知或其它消息,我们公司用的Oracle 9i 请问这个如何实现?   
答:可以用oracle里生成随机数的PL/SQL, 目录文件名在:/ORACLE_HOME/rdbms/admin/dbmsrand.sql。 
  用之前先要在sys用户下编译: 
  SQL>@/ORACLE_HOME/rdbms/admin/dbmsrand.sql 
  它实际是在sys用户下生成一个dbms_random程序包,同时生成公有同义词,并授权给所有数据库用户有执行的权限。 
  使用dbms_random程序包, 取出随机数据的方法: 
  1. 先创建一个唯一增长的序列号tmp_id 
  create sequence tmp_id increment by 1 start with 1 maxvalue 9999999 nocycle nocache; 
  2. 然后创建一个临时表tmp_1,把符合本次活动条件的记录全部取出来。 
  create table tmp_1 as select tmp_id.nextval as id,email,mobileno from 表名 where 条件; 
  找到最大的id号: 
  select max(id) from tmp_1; 
  假设为5000 
  3. 设定一个生成随机数的种子 
  execute dbms_random.seed(12345678); 
  或者 
  execute dbms_random.seed(TO_CHAR(SYSDATE,'MM-DD-YYYY HH24:MI:SS')); 
  4. 调用随机数生成函数dbms_random.value生成临时表tmp_2 
  假设随机取200个 
  create table tmp_2 as select trunc(dbms_random.value(1,5000)) as id from tmp_1 where rownum<201; 
  [ 说明:dbms_random.value(1,5000)是取1到5000间的随机数,会有小数, 
  trunc函数对随机数字取整,才能和临时表的整数ID字段相对应。 
  注意:如果tmp_1记录比较多(10万条以上),也可以找一个约大于两百行的表(假如是tmp_3)来生成tmp_2 
  create table tmp_2 as select trunc(dbms_random.value(1,5000)) as id from tmp_3 where rownum<201; ] 
  5. tmp_1和tmp_2相关联取得符合条件的200用户 
  select t1.mobileno,t1.email from tmp_1 t1,tmp_2 t2 where t1.id=t2.id; 
  [ 注意:如果tmp_1记录比较多(10万条以上),需要在id字段上建索引。] 
  也可以输出到文本文件: 
  set pagesize 300; 
  spool /tmp/200.txt; 
  select t1.mobileno,t1.email from tmp_1 t1,tmp_2 t2 where t1.id=t2.id order by t1.mobileno; 
  spool off; 
  6. 用完后,删除临时表tmp_1、tmp_2和序列号tmp_id。

延伸 · 阅读

精彩推荐