2015-07-11 103 views
0

我有这张表X只有一列,答:如何在特定值内的每行中生成一个随机数?比方说,我想随机数是1,2或999(3号),我想有一个B柱看起来像这样:SQL生成随机数

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

我已经试过dbms_random包,但只有到2之间产生数字如下:

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

有什么建议吗?

回答

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; 
+0

非常感谢您! – MrPedru22

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

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 |