【问题标题】:Data pivot in Oracle [closed]Oracle中的数据透视[关闭]
【发布时间】:2020-04-23 00:55:37
【问题描述】:

我有这样的数据:

| ITEM_CD |  CARACT_CD |   CARACT_VALUE     | DESCRIPTION |
|   1     |   A1       |   yyy              | descr1      |  
|   1     |   B1       |   xxx              | descr2      |  
|   2     |   A1       |   uuu              |             |  
|   2     |   B1       |   rrr              | descr3      |  
|   3     |   C1       |   kkk              |             |  

我希望将数据表示为:

| ITEM_CD |    A1      |   A1_DS     |    B1    |    B1_DS       |    C1    |    C1_DS       | 
|   1     |   yyy      |   descr1    |    xxx   |    descr2      |          |                |  
|   2     |   uuu      |             |    rrr   |    descr3      |          |                |  
|   3     |            |             |          |                |    kkk   |                |  

有人可以帮我使用 Oracle 中的 PIVOT 函数编写正确的查询吗?

非常感谢!

【问题讨论】:

标签: sql oracle pivot oracle12c


【解决方案1】:

我推荐条件聚合:

select item_cd,
       max(case when CARACT_CD = 'A1' then CARACT_VALUE end) as a1,
       max(case when CARACT_CD = 'A1' then DESCRIPTION end) as a1_desc,
       max(case when CARACT_CD = 'B1' then CARACT_VALUE end) as b1,
       max(case when CARACT_CD = 'B1' then DESCRIPTION end) as b1_desc,
       max(case when CARACT_CD = 'C1' then CARACT_VALUE end) as c1,
       max(case when CARACT_CD = 'C1' then DESCRIPTION end) as c1_desc
from t
group by item_cd;

我不推荐pivot。条件聚合可以完成它所做的一切——甚至更多——具有相似或更好的性能。

【讨论】:

  • 感谢您的帮助(以及我的请求的更新)。我会听从你的建议。
猜你喜欢
  • 1970-01-01
  • 2014-07-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-18
相关资源
最近更新 更多