How to select a repeatable random number with setseed in postgres sql?

*爱你&永不变心* 提交于 2019-12-12 17:29:31

问题


What I am trying to achieve is selecting a control group for a process. To do this I am using random(), and for debugging / consistency I would like to be able to set the random number in a repeatable fashion. Meaning, I run the query once it assigns user 123 random number .001. At a different time I delete the previous data, I call the same query, and once again user 123 is assigned random number .001.

I have tried:

SELECT setseed(0);
SELECT 1, random() from generate_series(1,10);

I receive a different random number with every run.

SELECT 1, setseed(0), random() from generate_series(1,10);

Each row receives the same random number, which is useless.

I'm sure there is something I don't understand here. Any help is appreciated.


回答1:


Do a union all of the setseed() query with the desired query. It is necessary to match the column types from both queries. setseed() returns void.

select setseed(0), null

union all

select null, random()
from generate_series(1, 10)

offset 1
;

The offset 1 clause eliminates the setseed() row from the result set



来源:https://stackoverflow.com/questions/25513452/how-to-select-a-repeatable-random-number-with-setseed-in-postgres-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!