【问题标题】:Array concatenation with distinct elements in BigQueryBigQuery 中具有不同元素的数组串联
【发布时间】:2019-10-02 02:50:14
【问题描述】:

假设在每一行中我有一个 id 和两个数组 array_1array_2,如下所示

SELECT 'a' id, [1,2,3,4,5] array_1, [2,2,2,3,6] array_2 UNION ALL
SELECT 'b', [2,3,4,5,6], [7,7,8,6,9] UNION ALL
SELECT 'c', [], [1,4,5]

我想连接这两个数组,并且只保留新数组中的唯一元素。我想要的输出如下所示

+----+-----------+-----------+-----------------------------+
| id |  array_1  |  array_2  | concatenated_array_distinct |
+----+-----------+-----------+-----------------------------+
| a  | 1,2,3,4,5 | 2,2,2,3,6 |                 1,2,3,4,5,6 |
| b  | 2,3,4,5,6 | 7,7,8,6,9 |             2,3,4,5,6,7,8,9 |
| c  |           |     1,4,5 |                       1,4,5 |
+----+-----------+-----------+-----------------------------+

我试图使用array_concat 函数,但我找不到使用array_concat 函数来保留不同元素的方法。

有没有我可以得到想要的输出?

【问题讨论】:

    标签: sql google-bigquery


    【解决方案1】:

    以下是 BigQuery 标准 SQL

    ... 我试图使用 array_concat 函数,但我找不到使用 array_concat 函数来保留不同元素的方法。 ...

    你在正确的轨道上:o)

    #standardSQL
    WITH `project.dataset.table` AS (
      SELECT 'a' id, [1,2,3,4,5] array_1, [2,2,2,3,6] array_2 UNION ALL
      SELECT 'b', [2,3,4,5,6], [7,7,8,6,9] UNION ALL
      SELECT 'c', [], [1,4,5]
    )
    SELECT *, 
      ARRAY(SELECT DISTINCT x 
        FROM UNNEST(ARRAY_CONCAT(array_1, array_2)) x 
        ORDER BY x
      ) concatenated_array_distinct
    FROM `project.dataset.table`  
    

    【讨论】:

      【解决方案2】:

      您可以使用unnest()union distinct

      with t as (
            select 'a' id, [1,2,3,4,5] array_1, [2,2,2,3,6] array_2 UNION ALL
            select 'b', [2,3,4,5,6], [7,7,8,6,9] UNION ALL
            select 'c', [], [1,4,5]
           )
      select t.*,
             (select array_agg( e.el)
              from (select el
                    from unnest(array_1) el
                    union distinct 
                    select el
                    from unnest(array_2) el
                   ) e 
             ) array_unique             
      from t
      

      【讨论】:

        【解决方案3】:

        简单、可读、可维护的解决方案:

        #Declare the function once
        #standardSQL
        CREATE TEMP FUNCTION dedup(val ANY TYPE) AS ((
          SELECT ARRAY_AGG(t)
          FROM (SELECT DISTINCT * FROM UNNEST(val) v) t
        ));
        
         with t as (
              select 'a' id, [1,2,3,4,5] array_1, [2,2,2,3,6] array_2 UNION ALL
              select 'b', [2,3,4,5,6], [7,7,8,6,9] UNION ALL
              select 'c', [], [1,4,5]
             )
         select t.*, 
                dedup(array_1 || array_2) array_unique 
         from t
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-02-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多