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

Azure Databricks SQL如何实现嵌套Struct数组转单层Struct数组

解决方案

无需修改源表结构,也不需要使用explode()(该函数会将数组元素拆分为独立行,不符合保留数组输出的需求)。你当前写的from_json已经可以正确解析原始嵌套结构,只需要在解析结果外嵌套transform高阶函数,遍历数组内每个元素提取嵌套字段,重组为扁平化结构即可。

可用查询语句

select 
  transform(
    from_json(
      Payload:Employees[*],
      'array<struct<`Person`:struct<`Name`:string,`Address`:struct<`Line1`:string,`Line2`:string>,`Service`:string>>',
      map('multiline', 'true')
    ),
    emp -> named_struct(
      'Name', emp.Person.Name,
      'Line1', emp.Person.Address.Line1,
      'Line2', emp.Person.Address.Line2,
      'Service', emp.Service
    )
  ) as flattened_employees
from delta.`/mnt/empsource`

实现逻辑

  • 原有from_json逻辑完全保留,负责将半结构化Payload字段解析为带明确类型的嵌套数组
  • transform逐行处理数组内的员工元素:
    • 提取Person.Name作为顶层Name字段
    • 提取Person.Address.Line1、Person.Address.Line2作为顶层地址字段
    • 直接保留原顶层的Service字段
    • 通过named_struct将上述字段组装为无嵌套的扁平化结构,最终返回长度和原数组一致、结构符合预期的新数组

输出结构

执行后返回的结构和目标要求完全匹配:

array
0:
--Name: value0
--Line1: value0
--Line2: value0
--Service: value0
1:
--Name: value1
--Line1: value1
--Line2: value1
--Service: value1

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 23:48:52