【问题标题】:Creating/Pivoting columns from Rows and Once Pivot created, I want to add values of different columns in the newly created column in SQL从行创建/透视列并创建透视后,我想在 SQL 中新创建的列中添加不同列的值
【发布时间】:2020-09-16 19:01:00
【问题描述】:

[我不允许复制图像,所以下面的链接有INout和Output1的图像

输入:

ColumnA   ColumnB  ColumnC  ColumnD 
1          India     DX       100  
2          India      AB       200
3          Aus       DX         300
4          Ger        BC        400

输出:

ColumnA  India  Aus  Ger  ColumnD
1         DX     -     -    100
2         AB     -      -    200
3         -      DX     -     300
4         -      -      BC     400

【问题讨论】:

  • 考虑处理应用代码中数据显示的问题

标签: mysql sql python-3.x pivot case


【解决方案1】:

您可以使用case 表达式来做到这一点:

select columna, 
    case when columnb = 'India' then columnc else '-' end india,
    case when columnb = 'Aus'   then columnc else '-' end aus,
    case when columnb = 'Ger'   then columnc else '-' end ger,
    columnd
from mytable

您的示例数据未显示,但您可能希望按columna 聚合:

select columna, 
    coalesce(max(case when columnb = 'India' then columnc end), '-') india,
    coalesce(max(case when columnb = 'Aus'   then columnc end), '-') aus,
    coalesce(max(case when columnb = 'Ger'   then columnc end), '-') ger
from mytable
group by columna

【讨论】:

  • @ GMB,工作。谢谢你。有没有一种方法可以为 50 多个国家/地区动态编码?
  • @rockstar:没有铅,那是我的错字。不,纯SQ没有短板,你需要重复max()表达式来处理更多的国家。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-16
  • 1970-01-01
  • 1970-01-01
  • 2021-04-06
  • 2018-03-26
相关资源
最近更新 更多