首页 > 解决方案 > 横向展平雪花中具有不同阵列长度的两列

问题描述

我是雪花的新手,目前正在学习使用横向扁平化。

我目前有一个看起来像这样的虚拟表: 在此处输入图像描述

用于“Customer_Number”和“Cities”的数据类型是数组。

我已经设法理解并应用 Flatten 概念来使用以下 sql 语句来分解数据:

select c.customer_id, c.last_name, f.value as cust_num, f1.value as city
    from customers as c,
    lateral flatten(input => c.customer_number) f,
    lateral flatten(input => c.cities) f1
    where f.index = f1.index
    order by customer_id;

显示的输出是: 在此处输入图像描述

从虚拟表中我们可以清楚地看到,在第 4 行 customer_id 104 有 3 个数字,我想在我的输出中看到这三个数字,如果城市中没有匹配的索引值,我只想看到“Null”在“城市”。

我的预期输出是: 在此处输入图像描述 这可能吗?

标签: snowflake-cloud-data-platform

解决方案


诀窍是删除第二个横向,并使用第一个的索引从第二个数组中选择值:

  select c.customer_id, c.last_name, f.value as cust_num, cites[f.index] as city
    from customers as c,
    lateral flatten(input => c.customer_number) f
    order by customer_id;

推荐阅读