sql - 从与分数成比例的组中抽取样本

标签 sql postgresql random google-bigquery sampling

我的数据具有以下结构:

CREATE TABLE if not EXISTS scores (
  id int,
  class char,
  score float
);

INSERT INTO scores VALUES
(1, 'A', 0.5),
(1, 'B', 0.2),
(1, 'C', 0.1),
(2, 'A', 0.1),
(2, 'B', 0.2),
(3, 'D', 0.01),
(4, 'A', 0.5),
(4, 'B', 0.5);

我想为每个 id 随机抽取一个类。获得的可能样本是:

1,'A'
2,'B'
3,'D'
4,'A'

我想要用于示例的逻辑如下:每个类都根据其分数按比例进行采样。例如:

  • id = 1 中,对“B”类进行采样的可能性应该是对“C”类进行采样的两倍。
  • id = 2 中,对“B”类进行采样的可能性应该是对“A”类进行采样的两倍。
  • id = 3 中,我们应该只对“D”类进行采样。
  • id = 4 中,采样类别“B”的可能性应与采样类别“A”的可能性相同。

我正在寻找在 BigQuery/PostgreSQL 中执行此操作的方法。另外,是否有可以重现的具有固定随机种子的解决方案?

谢谢!

最佳答案

可能的方法是为每个“id-class”对生成相当于分数的行数(50 个“1-A”行、20 个“1-B”行、10 个“1-C”行等) ...),然后每个 id 随机选择 1 行。

对于 BigQuery:

select id, array_agg(class order by rand() limit 1)[offset(0)]
from scores, unnest(generate_array(1, score * 100))
group by id

关于sql - 从与分数成比例的组中抽取样本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67786217/

相关文章:

php - 如何将数据从 PHP 插入到 MySQL DB

entity-framework - 首先为代码配置 EF 和 Npgsql

c++ - 在每台计算机上生成相同的随机排列

algorithm - 计算给定 rand7 的 rand5

php - 用户@localhost已经存在。无法为第二个数据库创建测试用户

sql - 检查sql语句是否已经执行

sql - 表的时间分布

ruby-on-rails - rails : Create a drop table cascade migration

postgresql - Postgres CTE : type character varying(255)[] in non-recursive term but type character varying[] overall

java - Hibernate 生成随机实体