简体   繁体   中英

How to select random row from table with non-uniform distribution, in Postgres?

This is how I would select a random row from a table with uniform distribution.

SELECT * FROM foo OFFSET floor( random() * ( SELECT COUNT(*) FROM foo ) ) ORDER BY bar LIMIT 1;

Let's say I would like to select a random row with a non-uniform distribution, say a normal distribution.

Currently, the way I am doing it is:

SELECT * FROM foo OFFSET floor( $1 * ( SELECT COUNT(*) FROM foo ) ) ORDER BY bar LIMIT 1;

... and work out the value for $1 prior to executing it.

  • Is there a better way to do this?
  • Perhaps using built in postgres functions?
  • Perhaps without the need for an inner SELECT statement?

Perhaps this entry from google books will be of help.

I believe you're looking for uniform/non-uniform as opposed to linear/non-linear, which probably hindered your search.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM