SQL生成随机数

时间:2015-07-11 15:13:16

标签: sql database oracle random

我的这个表X只有一列,A。如何在特定值内的每一行中生成一个随机数?假设我想要随机数字为1,2或999(3个数字),我会让B列看起来像这样:

A | B
-----
12| 1
33| 999
67| 1
20| 2
... 

我已经尝试了dbms_random包,但只生成2个数字,如下所示:

select X.*, round(dbms_random.value(1,2)) from X;

有什么建议吗?

3 个答案:

答案 0 :(得分:2)

以下是使用case的一种方法:

select x.a,
       (case when rand < 2 then 1 when rand < 3 then 2 else 999 end) as b
from (select x.*,
             dbms_random.value(1, 4) as rand
      from x
     ) x;

答案 1 :(得分:1)

您可以将所需的值(1,2,999,bla,bla,bla)存储在表格中,然后以随机顺序加入,例如:

create table x (a int);

insert into x values (12);
insert into x values (33);
insert into x values (67);
insert into x values (20);

create table y (z int);

insert into y values (1);
insert into y values (2);
insert into y values (999);

create table new_x as
select a,
       z
  from (select a,
               z,
               row_number() over(partition by a order by dbms_random.value) as rn
          from x
         cross join y)
 where rn = 1;

drop table x;

alter table new_x rename to x;

小提琴: http://www.sqlfiddle.com/#!4/8cf70/1/0

答案 2 :(得分:0)

SQL Fiddle

Oracle 11g R2架构设置

CREATE TABLE X ( A ) AS
SELECT LEVEL
FROM   DUAL
CONNECT BY LEVEL <= 20;

查询1

SELECT A,
       CASE FLOOR(DBMS_RANDOM.VALUE(1,4))
            WHEN 1 THEN 1
            WHEN 2 THEN 2
                   ELSE 999 END AS B
FROM   X

<强> Results

|  A |   B |
|----|-----|
|  1 |   1 |
|  2 |   2 |
|  3 | 999 |
|  4 | 999 |
|  5 |   2 |
|  6 |   1 |
|  7 | 999 |
|  8 | 999 |
|  9 | 999 |
| 10 | 999 |
| 11 |   1 |
| 12 |   1 |
| 13 | 999 |
| 14 |   2 |
| 15 |   1 |
| 16 |   2 |
| 17 |   2 |
| 18 | 999 |
| 19 |   1 |
| 20 | 999 |