使用SQL,我需要根据一些分配权重的基值生成N行的一些样本数据。
例如:如果我的基值及其相应的权重是:
如果所需的样本大小为15,则返回的行集应该有:
总共15行。
发布于 2019-05-31 00:15:25
在server中,您可以使用left,right来拆分值,然后使用cte + recursion get多个行,这种逻辑对于其他关系数据库管理系统也是常见的。
表& DDL
|val|
|--- |
|a-1|
|b-2|
|c-3|
|d-4|
|e-5|

查询SQL
with cte as (
select
left(val, CHARINDEX('-', val)-1) id
,convert(int, right(val, CHARINDEX('-', val)-1 )) cnt
from t
)
,cte2 as (
select T1.id,T1.cnt - 1 as cnt from cte T1
union all
select T1.id,T2.cnt - 1 as cnt from cte T1
inner join cte2 T2 on T1.id = T2.id and T2.cnt > 0
)
select id from cte2
order by id,cnt

发布于 2019-05-31 02:40:30
您需要一种生成行的方法,例如数字表。假设你有,那么问题就是算术(基本上)。
如果行数是权重之和的确切倍数,则以下操作很好:
select *
from (select t.*, sum(weight) over () as sum_weight,
sum(weight) over (order by rand()) as running_weight
from t
) t join
n
on n.n % sum_weight >= running_weight - weight and
n.n % sum_weight < running_weight
where n.n <= 15
order by value;这里是db<>fiddle。Fiddle使用Server,但这基本上是标准SQL。
https://stackoverflow.com/questions/56387026
复制相似问题