sql - 将 JSON 值列表分解为 SNOWFLAKE 数据库表中的行

标签 sql arrays json snowflake-cloud-data-platform

我按照下面的屏幕截图有一个表格,它基本上是一个 JSON 并被解析以获得下面的输出,现在我想要列 City 和 orders 中的值列表被拆分成行。
有人可以帮我吗
enter image description here
所需的输出如下
enter image description here

最佳答案

这是一种方法。首先去掉 ["和 ]"因为 city 列中的双引号不包含单个数组元素而是包含所有元素,然后将字符串标记化并使用 strtok_to_array 将其作为真实数组返回,然后将数组元素展平以分隔行并将行(城市)横向连接回记录的其余部分。

with data as
(select 'A' as name, 'M' as gender, '["completed"]' as orders, '["Cochi,Hyderabad"]' as city
union all
 select 'B' as name, 'M' as gender, '["completed"]' as orders, '["Cochi,Hyderabad,Delhi"]' as city
union all
 select 'C' as name, 'F' as gender, '["cancelled"]' as orders, '["Mumbai,Pune"]' as city
union all
 select 'D' as name, 'M' as gender, '["pending"]' as orders, '["cochi"]' as city
)
, data2 as 
( select d.name
 , d.gender
 , replace(replace(d.orders,'["',''),'"]','') as orders
 , strtok_to_array(replace(replace(city,'["',''),'"]',''),',')  as city
 from data d
)
 select d2.name
 , d2.gender
 , d2.orders
 , replace(c.value,'"','') as city
 from data2 d2
  , lateral flatten(input => d2.city) c;

关于sql - 将 JSON 值列表分解为 SNOWFLAKE 数据库表中的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69676196/

相关文章:

多边形内的SQL Geography点在ST​​Intersect上不返回true(但使用Geometry返回true)

SQL Server 将前导零添加到一位数月份

javascript - Jquery - 选择选项时填写输入文本

Java n 数组中最年轻和最老的

javascript - 更改排序顺序时更新键值的最短方法是什么

c# - 在 C# 中从 JSON 对象转换为 expando 对象

javascript - Chrome扩展程序的内容脚本不会影响特定网站

mysql - 为什么 SQL 条件不匹配 "OR"子句?

sql - 从两个表中查找日期时间之间的时间间隔

javascript - 为什么 Angularjs 指令会变成 html 注释?