SQL Pivot 行到列标题
Posted
技术标签:
【中文标题】SQL Pivot 行到列标题【英文标题】:SQL Pivot rows to column header 【发布时间】:2021-05-08 21:50:22 【问题描述】:我需要隔离 (ATR,AWT) 中的 sales_credit_type_code 为每个 customer_key 创建 4 个新列。
当前表
期望的输出
这是我的代码不起作用:
SELECT customer_key,
CASE sales_credit_type_code WHEN 'ATR' THEN dm_name END AS 'ATR DM Name',
CASE sales_credit_type_code WHEN 'ATR' THEN salesrep_name END AS 'ATR Salesrep Name',
CASE sales_credit_type_code WHEN 'AWT' THEN dm_name END AS 'AWT DM Name',
CASE sales_credit_type_code WHEN 'AWT' THEN salesrep_name END AS 'AWT Salesrep Name'
FROM aim_customer_zipterr_xref_transposed_vw
group by 1,2,3,4,5
【问题讨论】:
【参考方案1】:你可以使用聚合函数group_concat
:
select customer_key ,
group_concat(CASE sales_credit_type_code WHEN 'ATR' THEN dm_name END, ',') AS 'ATR DM Name',
group_concat(CASE sales_credit_type_code WHEN 'ATR' THEN salesrep_name END,',') AS 'ATR Salesrep Name',
group_concat(CASE sales_credit_type_code WHEN 'AWT' THEN dm_name END, ',') AS 'AWT DM Name',
group_concat(CASE sales_credit_type_code WHEN 'AWT' THEN salesrep_name END, ',') AS 'AWT Salesrep Name'
FROM aim_customer_zipterr_xref_transposed_vw
group by customer_key
更多信息:impala doc
或者如果每种类型都有一个:
select customer_key ,
max(CASE sales_credit_type_code WHEN 'ATR' THEN dm_name END) AS 'ATR DM Name',
max(CASE sales_credit_type_code WHEN 'ATR' THEN salesrep_name END,',') AS 'ATR Salesrep Name',
max(CASE sales_credit_type_code WHEN 'AWT' THEN dm_name END) AS 'AWT DM Name',
max(CASE sales_credit_type_code WHEN 'AWT' THEN salesrep_name END) AS 'AWT Salesrep Name'
FROM aim_customer_zipterr_xref_transposed_vw
group by customer_key
【讨论】:
谢谢你,@eshirvana。结果在 select 语句中的其他维度上重复。有什么方法可以使 group_concat 结果不同?我试过: group_concat(Distinct CASE sales_credit_type_code WHEN 'ATR' THEN dm_name END, ',') AS 'Acute RSM', group_concat(Distinct CASE sales_credit_type_code WHEN 'ATR' THEN salesrep_name END,',') AS 'Acute Rep', group_concat (Distinct CASE sales_credit_type_code WHEN 'AWT' THEN dm_name END, ',') AS 'OOH RSM', group_concat(Distinct CASE sales_credit_type_code WHEN 'AWT' THEN salesrep_name END, ',') AS 'OOH Rep', @ChaseMekaelian,如果你的意思是你得到重复的行,那么根据提供的示例数据,你不应该,除非有更多的故事;),也许提供更好的示例数据 也尝试了 max 函数,它不能与字符串一起工作以上是关于SQL Pivot 行到列标题的主要内容,如果未能解决你的问题,请参考以下文章