Results 1 to 3 of 3

Thread: weighted random

  1. #1
    Join Date
    Jun 2015
    Posts
    4

    Unanswered: weighted random

    Code:
    (id) country
    
    (1) Korea
    (2) Japan
    (3) America
    (4) France
    I have a table named "country" like the above.

    The code below produces a country randomly.
    Code:
    select country from test
    order by rand() limit 1

    The following code doesn't work correctly, but it shows what I want.

    Code:
    select country from test
    order by rand(America=50%, France30%) limit 1
    If I see the result 10 times,
    America comes about 5 Times
    France comes about 3 Times
    Korea and Japan comes about 1 time.

    What SQL get the my target result?

  2. #2
    Join Date
    Jun 2016
    Posts
    4
    Provided Answers: 1
    Try this:

    Code:
    set @rand_val := round(rand() * 10);
    select
    	case
    		when @rand_val between 0 and 4
            then 'America'
            when @rand_val between 5 and 7
            then 'France'
            when @rand_val = 8
            then 'Korea'
            else 'Japan'
    	end as `Country`;

  3. #3
    Join Date
    Jun 2016
    Posts
    4
    Provided Answers: 1
    Try this:

    Code:
    set @pick := round(rand()*9);
    select
    	case
    		when @pick between 0 and 4
    		then 'America'
    		when @pick between 5 and 7
    		then 'France'
    		when @pick = 8
    		then 'Japan'
    		when @pick = 9
    		then 'Korea'
    	end as `Country`;

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •