在 BigQuery 中进行随机替换抽样的最有效方法是什么?

Max*_*Max 3 sql google-bigquery

此问题的答案解释了如何从 BigQuery 表中随机采样。有没有一种有效的方法可以通过替换来做到这一点?

例如,假设我有一个包含 1M 行的表,并且我希望选择 100K 独立随机采样的行。

Max*_*Max 6

找到了一个巧妙的解决方案:

  • 对表的行建立索引
  • 生成一个包含 100K 1 到 1M 之间随机整数的虚拟表
  • 索引上的表内连接 = 随机值

代码:

# randomly sample 100K rows from `table` with replacement
with large_table as (select *, row_number() over() as rk from `table`),
num_elements as (select count(1) as n from large_table),
dummy_table as (select 1 + cast(rand() * (select n - 1 from num_elements) as int64) as i from unnest(generate_array(1, 100000)))
select * from dummy_table
inner join large_table on dummy_table.i = large_table.rk
Run Code Online (Sandbox Code Playgroud)