Generate a random number in the range 1 - 10

前端 未结 7 2001
-上瘾入骨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:56

    The correct version of hythlodayr's answer.

    -- ERROR:  operator does not exist: double precision % integer
    -- LINE 1: select (trunc(random() * 10) % 10) + 1
    

    The output from trunc has to be converted to INTEGER. But it can be done without trunc. So it turns out to be simple.

    select (random() * 9)::INTEGER + 1
    

    Generates an INTEGER output in range [1, 10] i.e. both 1 & 10 inclusive.

    For any number (floats), see user80168's answer. i.e just don't convert it to INTEGER.

提交回复
热议问题