Re: advice on weighted random selection - Mailing list pgsql-general

From Manfred Koizar
Subject Re: advice on weighted random selection
Date
Msg-id 2sio6v4jujtl12lh7mp38cjdd2hfhvoh72@4ax.com
Whole thread Raw
In response to advice on weighted random selection  (Jeff Davis <jdavis-pgsql@empires.org>)
List pgsql-general
On Sun, 9 Mar 2003 13:40:30 -0800, Jeff Davis
<jdavis-pgsql@empires.org> wrote:
>I would like to select (data1,data2) from a random record, but I'd like (1,2)
>to be 3.44 times as likely as (5,6). I would also like (7,8) to be 2 times as
>likely as (5,6), and (1,2) to be 1.72 times as likely as (7,8).

If you had

data1   data2     weight  minw  maxw
--------------------------------------
1         2        3.44   0.00  3.44
3         4        0.94   3.44  4.38
5         6        1.00   4.38  5.38
7         8        2.00   5.38  7.38

and an immutable wrapper function around random(), you could

    SELECT data1, data2
      FROM t
     WHERE minw < myrandom(7.38) AND myrandom(7.38) <= maxw;

Make sure myrandom() never returns 0.00 or set minw to something less
than 0.00 in the first row.

Servus
 Manfred

pgsql-general by date:

Previous
From: "frank_lupo"
Date:
Subject: function param problem in 7.3
Next
From: "shreedhar"
Date:
Subject: Re: foreign SERIAL keys in weak entity primary keys