生成1-10范围内的随机数 [英] Generate a random number in the range 1 - 10
本文介绍了生成1-10范围内的随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
由于我在此问题中进行过测试查询,所以无法解决,我现在正在尝试其他方法。有没有办法告诉pg的 random()
函数让我只得到1到10之间的数字?
Since my approach for a test query which I worked on in this question did not work out, I'm trying something else now. Is there a way to tell pg's random()
function to get me only numbers between 1 and 10?
推荐答案
如果按1到10之间的数字表示,则任何大于等于1且小于< 10,这很容易:
If by numbers between 1 and 10 you mean any float that is >= 1 and < 10, then it's easy:
select random() * 9 + 1
可以很容易地通过以下方法进行测试:
This can be easily tested with:
# select min(i), max(i) from (
select random() * 9 + 1 as i from generate_series(1,1000000)
) q;
min | max
-----------------+------------------
1.0000083274208 | 9.99999571684748
(1 row)
如果要使用整数,则> = 1和< ; 10,那么很简单:
If you want integers, that are >= 1 and < 10, then it's simple:
select trunc(random() * 9 + 1)
再次,简单测试:
# select min(i), max(i) from (
select trunc(random() * 9 + 1) as i from generate_series(1,1000000)
) q;
min | max
-----+-----
1 | 9
(1 row)
这篇关于生成1-10范围内的随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文