如何将每行中多个不同长度的数组转换为列?
调整后的查询语句
with `mydata.data` as ( select [1] as ArrayA, [1,2,3] ArrayB, 'AA' columnString1, 'ABA' columnString2 union all select [6,3,3], [5,6,7,4] ,'AA','ABC' ) select * from ( select columnString1, columnString2, a.val as ArrayA, b.val as ArrayB, coalesce(a.offset, b.offset) as offset from `mydata.data` left join unnest(ArrayA) as val with offset a on true full join unnest(ArrayB) as val with offset b on a.offset = b.offset ) pivot ( ANY_VALUE(ArrayA) ArrayA, ANY_VALUE(ArrayB) ArrayB for offset in (0, 1, 2, 3) )
核心调整说明
原查询使用内连接join unnest(ArrayB),只会保留两个数组**同时存在对应偏移量(offset)**的行,直接丢弃了长数组中超出短数组长度的元素。
改为**全连接(full join)**后,两个数组的所有偏移量都会被保留:
- 若某偏移量仅在ArrayA中存在,ArrayB对应位置为null
- 若某偏移量仅在ArrayB中存在,ArrayA对应位置为null
- 通过
coalesce(a.offset, b.offset)统一偏移量值,确保后续pivot能正确匹配位置
同时修正了原CTE中最后一行的多余逗号,避免语法错误。
内容的提问来源于stack exchange,提问作者jake_jj
相关产品推荐
相关产品推荐

