0

我正在加入 2 个表,连接在左侧,第二个表没有第一个表的所有键,因此在右侧会产生 NULL。将其分组为数组时如何避免它们?

例如:

with 
  t1 AS (select 1 AS c1, 2 AS c2 UNION ALL select 5, 6),
  t2 AS (select 3 AS c1, 4 AS c4 UNION ALL select 3, 5, UNION ALL select 3,4, UNION ALL select 5,6)
SELECT t2.c1, ARRAY_AGG(DISTINCT t2.c4), ARRAY_AGG((SELECT AS STRUCT t1.*))
FROM t2 LEFT JOIN t1 ON t1.c1=t2.c1
GROUP BY t2.c1

结果是:

在此处输入图像描述

我期望的是,第一行对于第二个表只有一行 NULL,smth 就像(对不起,糟糕的图纸):

在此处输入图像描述

4

1 回答 1

1

删除所有空语句可以吗?

然后if在里面使用一个语句array_agg

with 
  t1 AS (select 1 AS c1, 2 AS c2 UNION ALL select 5, 6),
  t2 AS (select 3 AS c1, 4 AS c4 UNION ALL select 3, 5, UNION ALL select 3,4, UNION ALL select 5,6)
SELECT t2.c1, ARRAY_AGG(DISTINCT t2.c4), ARRAY_AGG( if(t1.c1 is null   , null, STRUCT(t1) ) ignore nulls  ), 
FROM t2 LEFT JOIN 
t1 
 ON t1.c1=t2.c1

GROUP BY t2.c1
于 2021-08-17T21:09:02.403 回答