2009-10-14 265 views
15

我要选择一个表,然后在1〜9之间的随机数的所有行:生成随机数在每一行中的Oracle查询

select t.*, (select dbms_random.value(1,9) num from dual) as RandomNumber 
from myTable t 

但随机数是排在同一排,仅与查询的每次运行不同。在同一个执行过程中,如何使每行的行数不同?

+0

只需要清楚,'dbms_random.value()'调用只执行一次,因为th e'select'在外部'select'之前被评估。 – 2009-10-14 20:07:51

回答

25

喜欢的东西?

select t.*, round(dbms_random.value() * 8) + 1 from foo t; 
+2

dbms_random.value(1,9)语法仍然正确。它只是子查询结构是错误的 – 2009-10-14 23:32:40

+0

啊,不是数值的均匀分布 – 2009-10-15 08:17:28

6

你不需要select … from dual,只写:

SELECT t.*, dbms_random.value(1,9) RandomNumber 
    FROM myTable t 
+0

啊,太好了。我怎么生成从1到9而不是浮动的随机整数? – Saobi 2009-10-14 20:07:53

+0

use round ... aaah,too late :( – knittl 2009-10-14 20:35:59

14

起初我以为这会工作:

select DBMS_Random.Value(1,9) output 
from ... 

不过,这并不会产生甚至输出值的分布:

select output, 
     count(*) 
from (
     select round(dbms_random.value(1,9)) output 
     from dual 
     connect by level <= 1000000) 
group by output 
order by 1 

1 62423 
2 125302 
3 125038 
4 125207 
5 124892 
6 124235 
7 124832 
8 125514 
9 62557 

的原因是很明显的,我认为。

我建议使用类似:

floor(dbms_random.value(1,10)) 

因此:

select output, 
     count(*) 
from (
     select floor(dbms_random.value(1,10)) output 
     from dual 
     connect by level <= 1000000) 
group by output 
order by 1 

1 111038 
2 110912 
3 111155 
4 111125 
5 111084 
6 111328 
7 110873 
8 111532 
9 110953 
+2

dbms_random.value(1, 10)可能更正确,因为根据[10.2 docs](http://docs.oracle.com/cd/B19306_01/appdev.102/),结果x大于或等于第一个参数,小于第二个参数b14258/d_random.htm#i998095) – jswolf19 2014-02-14 07:05:35

2

如果你只是使用圆形,然后在两个端数字(1和9)会较少发生,得到1到9之间的整数均匀分布:

SELECT MOD(Round(DBMS_RANDOM.Value(1, 99)), 9) + 1 FROM DUAL 
+0

不错,非常有用。 – 2016-04-20 08:43:40