You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Snowflake中Variant列使用Lateral Flatten避免笛卡尔积,获取对应行

解决方案

要避免笛卡尔积、得到按数组位置对齐的3行结果,需通过索引关联三个列的展开数据,具体实现如下:

核心思路

对每个数组列执行flatten时保留元素的索引,再以索引为关联条件,将三个展开结果进行连接,确保同一索引位置的元素出现在同一行。

示例SQL

select 
    pc.value::string as column1,
    pc1.value::string as column2,
    pc2.value::string as column3
from table as RCV 
-- 展开Column1并保留索引
lateral flatten(input=>RCV.column1, with index) PC
-- 按索引关联Column2的展开结果
full outer join lateral flatten(input=>RCV.column2, with index) PC1
    on PC.index = PC1.index
-- 按索引关联Column3的展开结果
full outer join lateral flatten(input=>RCV.column3, with index) PC2
    on coalesce(PC.index, PC1.index) = PC2.index
-- 按索引排序,保证结果顺序正确
order by coalesce(PC.index, PC1.index, PC2.index);

结果说明

执行后会得到3行数据,对应数组的三个索引位置:

  • 索引0:5, 3, 4
  • 索引1:55, 52, 53
  • 索引2:null, 66, null

若不需要null值,可根据需求用nvl等函数替换空值。

内容的提问来源于stack exchange,提问作者user1526892

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 10:15:54