【问题标题】:Bigquery UDF to repeat queries. Error : Scalar subquery cannot have more than one columnBigquery UDF 重复查询。错误:标量子查询不能超过一列
【发布时间】:2021-10-13 09:22:19
【问题描述】:

我试图从多个列中获取唯一值,但由于数据结构是一个数组,我不能直接在所有列上执行 DISTINCT。我为每一列使用UNNEST(),并为每一列执行UNION ALL

我的想法是创建一个 UDF,这样我每次都可以简单地给出列名,而不是每次都执行选择。

我想用 UDF 替换这个查询,因为有很多特征列,我需要做很多 UNION ALL。


SELECT DISTINCT user_log as unique_value,
    'user_log' as feature        
FROM `my_table`
left join UNNEST(user_Log) AS user_log
union all 
SELECT DISTINCT page_name as unique_value,
    'user_login_page_name' as feature        
FROM `my_table`
left join UNNEST(PageName) AS page_name
order by feature;

我的 UDF

CREATE TEMP FUNCTION get_uniques(feature_name ARRAY<STRING>, feature STRING)
AS (
(SELECT DISTINCT feature as unique_value,
    'feature' as feature        
FROM `my_table`
left join UNNEST(feature_name) AS feature));

SELECT get_uniques(user_Log, log_feature);

但是选择列的 UDF 并没有真正起作用并给出错误 Scalar subquery cannot have more than one column unless using SELECT AS STRUCT to build STRUCT values; failed to parse CREATE [TEMP] FUNCTION statement at [8:1]

可能有更好的方法来做到这一点。感谢您的帮助。

【问题讨论】:

  • 你想在一个单一的选择语句中这样做还是你也可以有脚本语句?
  • 你想要一个函数来打印你的结构值的列或这些列的数据吗?另外,您希望通过创建这样的功能来实现什么?即: select (id) from get_unique(user_log,id) union all select (page_name) from get_getunique(page,page_name)

标签: google-bigquery


【解决方案1】:

通过阅读您想要实现的目标,即:

My idea is to create a UDF so that i can simply give the column name each time instead of performing the select every time.

一种方法是结合使用格式和立即执行来创建您的自定义查询并获得所需的输出。

下面的示例显示了使用格式返回自定义查询并立即执行以从最终表中检索最终查询输出的函数。我正在使用 public 数据集,因此您也可以自己尝试一下:

CREATE TEMP FUNCTION GetUniqueValues(table_name STRING, col_name STRING, nest_col_name STRING) 
AS (format("SELECT DISTINCT %s.%s as unique_val,'%s' as featured  FROM %s ", col_name,nest_col_name,col_name,table_name));


EXECUTE IMMEDIATE (
select CONCAT(
    (SELECT GetUniqueValues('bigquery-public-data.github_repos.commits','Author','name'))
    ,' union all '
    ,(SELECT GetUniqueValues('bigquery-public-data.github_repos.commits','Committer','name'))
    ,' limit 100'))

输出

Row  | unique_val            | featured 
1    | Sergio Garcia Murillo | Committer
2    | klimek                | Committer
3    | marclaporte@gmail.com | Committer
4    | acoul                 | Committer
5    | knghtbrd              | Committer
...  | ...                   | ...
100  | Gustavo Narea         | Committer

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-13
    • 1970-01-01
    相关资源
    最近更新 更多