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

Azure Databricks中SQL分组特定列并透视其他列的实现方法

在Azure Databricks中实现SQL透视转换需求

解决方案SQL代码

SELECT 
  clientid,
  visitid,
  channel,
  conversion,
  `11` AS `salary (index=11)`,
  `22` AS `savings (index=22)`,
  `33` AS `salary range (index=33)`
FROM tb_user_info
PIVOT (
  MAX(value) FOR index IN (11, 22, 33)
) AS pivoted_table
ORDER BY clientid;

代码说明

  • 分组逻辑:clientid, visitid, channel, conversion作为分组列,PIVOT子句会自动基于这些列对数据进行分组聚合。
  • 透视处理:PIVOT子句中,MAX(value)用于提取每个分组下对应index的唯一value(因为每个分组内每个index仅出现一次,使用MAX/FIRST/MIN均可);FOR index IN (11,22,33)指定需要转换为列的index值。
  • 列重命名:通过AS将透视生成的原始列名(11、22、33)替换为需求中的友好名称。
  • 排序:最后通过ORDER BY clientid保证结果顺序与预期一致。

执行结果

clientidvisitidchannelconversionsalary (index=11)savings (index=22)salary range (index=33)
123abc123google11250250001K and 3K
456def456facebook32860780003K and 5K

注:您提供的期望输出中clientid=456的conversion值为1,与原数据集的3不符,上述结果以原数据集为准。

内容的提问来源于stack exchange,提问作者Wagner André Yamada Vieira

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 00:20:38