比方说,我在每一行中都有一个id
和两个数组array_1
和array_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
函数保留不同元素的方法。
反正我能得到想要的输出吗?
答案 0 :(得分:1)
您可以使用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
答案 1 :(得分: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`