如何在 BigQuery 中使用随机数创建多个数组

How to create multiple arrays with random numbers in BigQuery

我有以下代码,其中我创建了 3 个长度分别为 5、10 和 15 的随机数组。

with example as (
    select 1 as id, mod(cast(10*rand() as int64), 10) as random_array from unnest(generate_array(1, 5))
    union all select 2 as id, mod(cast(10*rand() as int64), 10) from unnest(generate_array(1, 10))
    union all select 3 as id, mod(cast(10*rand() as int64), 10) from unnest(generate_array(1, 15))
    )

select 
    id,
    array_agg(random_array) as nested_numbers
from unnesting_example
group by id

有没有一种(更聪明的)方法可以通过在 with 子句中创建数组来做到这一点?那么,不使用额外的 select?谢谢

您可以使用STRUCT

SELECT * FROM UNNEST([
  STRUCT(1 AS id, ARRAY((SELECT mod(cast(10*rand() as int64), 10) FROM UNNEST(GENERATE_ARRAY(1, 5)))) AS random_arr),
  STRUCT(2 AS id, ARRAY((SELECT mod(cast(10*rand() as int64), 10) FROM UNNEST(GENERATE_ARRAY(1, 10)))) AS random_arr),
  STRUCT(3 AS id, ARRAY((SELECT mod(cast(10*rand() as int64), 10) FROM UNNEST(GENERATE_ARRAY(1, 15)))) AS random_arr)
])

输出

id random_arr
1 [2,2,7,3,5]
2 [8,5,8,2,1,1,7,3,9,8]
3 [9,1,7,0,2,1,6,6,7,8,8,0,2,4,1]

考虑以下

select id, 
  array(
    select mod(cast(10 * rand() as int64), 10) 
    from unnest(generate_array(1, len) )
  ) as random_arr
from unnest([struct<id int64, len int64>(1,5), (2,10), (3,15)])       

有输出