如何在BigQuery中连接两个不同数据类型的数组?

时间:2019-01-25 23:09:48

标签: arrays google-bigquery standard-sql

当我尝试连接两个相同数据类型的数组时,它工作得很好。

示例如下所示

#standardSQL
WITH
  table1 AS (
  SELECT 'a' id UNION ALL
  SELECT 'b' UNION ALL
  SELECT 'c'
  ),
  table2 AS (
  SELECT 'a' id, [1,2,3,4,5] array_1 UNION ALL
  SELECT 'b', [1,2,3,4,5] UNION ALL
  SELECT 'c', [1,2,3,4,5]
  ),
  table3 AS (
  SELECT 'a' id, [10,20,30,40,50] array_2 UNION ALL
  SELECT 'b', [10,20,30,40,50] UNION ALL
  SELECT 'c', []
  ),
  joined_table as (
  select table1.id,
  table2.array_1,
  table3.array_2
  from 
    table1
  JOIN table2
  USING(id)
  JOIN table3
  using(id)
  )
SELECT
  joined_table.*,
  ARRAY_CONCAT(IFNULL(joined_table.array_1,[]), IFNULL(joined_table.array_2,[])) as concatanated_arrays
  FROM joined_table

但是当我尝试进行连接时,数组却具有不同的数据类型,例如下面的示例查询:

#standardSQL
WITH
  table1 AS (
  SELECT 'a' id UNION ALL
  SELECT 'b' UNION ALL
  SELECT 'c'
  ),
  table2 AS (
  SELECT 'a' id, [1,2,3,4,5] array_1 UNION ALL
  SELECT 'b', [1,2,3,4,5] UNION ALL
  SELECT 'c', [1,2,3,4,5]
  ),
  table3 AS (
  SELECT 'a' id, ['10','20','30','40','50'] array_2 UNION ALL
  SELECT 'b', ['10','20','30','40','50'] UNION ALL
  SELECT 'c', []
  ),
  joined_table as (
  select table1.id,
  table2.array_1,
  table3.array_2
  from 
    table1
  JOIN table2
  USING(id)
  JOIN table3
  using(id)
  )
SELECT
  joined_table.*,
  ARRAY_CONCAT(IFNULL(joined_table.array_1,[]), IFNULL(joined_table.array_2,[])) as concatanated_arrays
  FROM joined_table

我的查询没有运行并显示如下错误:

Error: No matching signature for function ARRAY_CONCAT for argument types: ARRAY<INT64>, ARRAY<STRING>. Supported signature: ARRAY_CONCAT(ARRAY, [ARRAY, ...]) at [31:3]

如何串联这两个不同类型的数组?

2 个答案:

答案 0 :(得分:1)

BigQuery中无法连接具有不同数据类型的数组。连接数组时,您需要数据类型相同。

解决当前问题的一种方法是将整数数组转换为字符串,然后将它们连接起来以获得组合数组。

以下查询可在BigQuery standard-sql中使用,以演示一个这样的示例:

#standardSQL
WITH
  table1 AS (
  SELECT 'a' id UNION ALL
  SELECT 'b' UNION ALL
  SELECT 'c'
  ),
  table2 AS (
  SELECT 'a' id, [1,2,3,4,5] array_1 UNION ALL
  SELECT 'b', [1,2,3,4,5] UNION ALL
  SELECT 'c', [1,2,3,4,5]
  ),
  table3 AS (
  SELECT 'a' id, ['10','20','30','40','50'] array_2 UNION ALL
  SELECT 'b', ['10','20','30','40','50'] UNION ALL
  SELECT 'c', []
  ),
  joined_table as (
  select table1.id,
  table2.array_1,
  table3.array_2
  from 
    table1
  JOIN table2
  USING(id)
  JOIN table3
  using(id)
  )
SELECT
  joined_table.*,
  ARRAY_CONCAT(IFNULL(ARRAY(SELECT CAST(value as string) FROM UNNEST(joined_table.array_1) value),[]), IFNULL(joined_table.array_2,[])) as concatanated_arrays
  FROM joined_table

但是最终,concatenated_arrays变成了重复的字符串字段。

答案 1 :(得分:1)

替代(较浅)的版本-BigQuery标准SQL

BLE

如果要应用于有问题的样本数据-产生预期结果