Select random row from a PostgreSQL table with weighted row probabilities

后端 未结 6 1910
耶瑟儿~
耶瑟儿~ 2020-12-03 17:30

Example input:

SELECT * FROM test;
 id | percent   
----+----------
  1 | 50 
  2 | 35   
  3 | 15   
(3 rows)

How would you write such query, that

6条回答
  •  渐次进展
    2020-12-03 18:03

    Here is something for you to play with:

    select t1.id as id1
      , case when t2.id is null then 0 else t2.id end as id2
      , t1.percent as percent1
      , case when t2.percent is null then 0 else t2.percent end as percent2 
    from "Test1" t1 
      left outer join "Test1" t2 on t1.id = t2.id + 1
    where random() * 100 between t1.percent and 
      case when t2.percent is null then 0 else t2.percent end;
    

    Essentially perform a left outer join so that you have two columns to apply a between clause.

    Note that it will only work if you get your table ordered in the right way.

提交回复
热议问题