BigQuery 用户定义的聚合函数?
BigQuery User Defined Aggregation Function?
我知道我可以定义一个 User Defined Function in order to perform some custom calculation. I also know I can use the 'out-of-the-box' aggregation functions 来在使用 GROUP BY
子句时将值的集合减少为单个值。
是否可以定义自定义的用户定义聚合函数以与 GROUP BY
子句一起使用?
事实证明这是可能的(只要我们寻求聚合的组在内存中具有合理的大小)一点点 'glue' - 即 ARRAY_AGG
函数
步骤如下:
- 使用
ARRAY<T>
类型的输入参数创建一个 UDF,其中 T
是您要聚合的值的类型。
- 在带有
GROUP BY
子句的查询中使用 ARRAY_AGG
函数生成一个 T
数组并传递到您的 UDF。
举个具体的例子:
CREATE TEMP FUNCTION aggregate_fruits(fruits ARRAY<STRING>)
RETURNS STRING
LANGUAGE js AS """
return "my fruit bag contains these items: " + fruits.join(",");
""";
WITH fruits AS
(SELECT "apple" AS fruit
UNION ALL SELECT "pear" AS fruit
UNION ALL SELECT "banana" AS fruit)
SELECT aggregate_fruits(ARRAY_AGG(fruit))
FROM fruits
我知道我可以定义一个 User Defined Function in order to perform some custom calculation. I also know I can use the 'out-of-the-box' aggregation functions 来在使用 GROUP BY
子句时将值的集合减少为单个值。
是否可以定义自定义的用户定义聚合函数以与 GROUP BY
子句一起使用?
事实证明这是可能的(只要我们寻求聚合的组在内存中具有合理的大小)一点点 'glue' - 即 ARRAY_AGG
函数
步骤如下:
- 使用
ARRAY<T>
类型的输入参数创建一个 UDF,其中T
是您要聚合的值的类型。 - 在带有
GROUP BY
子句的查询中使用ARRAY_AGG
函数生成一个T
数组并传递到您的 UDF。
举个具体的例子:
CREATE TEMP FUNCTION aggregate_fruits(fruits ARRAY<STRING>)
RETURNS STRING
LANGUAGE js AS """
return "my fruit bag contains these items: " + fruits.join(",");
""";
WITH fruits AS
(SELECT "apple" AS fruit
UNION ALL SELECT "pear" AS fruit
UNION ALL SELECT "banana" AS fruit)
SELECT aggregate_fruits(ARRAY_AGG(fruit))
FROM fruits