Generate a random number in the range 1 - 10

前端 未结 7 2000
-上瘾入骨i
-上瘾入骨i 2020-12-04 11:32

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() fu

7条回答
  •  星月不相逢
    2020-12-04 11:53

    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)
    

    If you want integers, that are >= 1 and < 10, then it's simple:

    select trunc(random() * 9 + 1)
    

    And again, simple test:

    # 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)
    

提交回复
热议问题