select e.*, t2.*
from (
select event,
(select coalesce(sum(chance_percentage), 0)
from table1 t2 where t2.event < t1.event) as lower_bound,
(select sum(chance_percentage)
from table1 t3 where t3.event <= t1.event) as upper_bound
from table1 t1) e
join (select 100.0 * rand() as p) t2
where t2.p >= e.lower_bound and t2.p < e.upper_bound;
select t.event
from (select t.*, (@cume_p = @cume_p + p) as cume_p
from t cross join
(select @cume_p := 0, @rand = rand()) params
) t
where @rand >= cume_p - p and
@rand < cume_p;
请注意 rand() 只叫过一次。该值存储在变量中;这是一个任意的选择。也可以在子查询中:
select t.event
from (select t.*, (@cume_p = @cume_p + p) as cume_p
from t cross join
(select @cume_p := 0) params
) t cross join
(select rand() as r) r
where r.r >= cume_p - p and
r.r < cume_p;
SELECT Event
FROM Your_Table
WHERE CASE WHEN Event = 'A' THEN
CASE WHEN RAND() <= .25 THEN 1
END
WHEN Event = 'B' THEN
CASE WHEN RAND() <= .1 THEN 1
END
WHEN Event = 'C' THEN
CASE WHEN RAND() <= .15 THEN 1
END
WHEN Event = 'D' THEN
CASE WHEN RAND() <= .5 THEN 1
END
END = 1;
5条答案
按热度按时间blpfk2vs1#
更通用的解决方案是:
lnlaulya2#
做一个累加和然后运行
rand()
一次:请注意
rand()
只叫过一次。该值存储在变量中;这是一个任意的选择。也可以在子查询中:w8ntj3qf3#
我没有在我的机器上安装mysql,所以这是未经测试的,但我认为这个一般的想法将工作。
pqwbnv8z4#
在应用程序编程语言(如java、python、c、php、javascript或您正在使用的其他语言)中,这应该很容易计算。您只需选择应用程序中的所有行,然后在易于编写的地方进行计算。
如果没有应用程序需要在数据库中执行,那么就不要这样做。为正确的工作使用正确的工具。数据库首先用于持久性,而不是计算。
另请参见xy问题。
tjrkku2a5#
如果您只想选择一个概率等于百分比的字段
我认为这样做很好:设置@mybound:=rand()100;选择from event where chance\u percentage<@mybound order by chance\u percentage desc limit 1