当前位置:   article > 正文

Oracle 行转列、列转行详解(pivot、unpivot)

oracle 行转列

1 概述

行列互换
行转列:pivot
列的个数必须已知
列转行:unpivot
新增列

2 示例

2.1 pivot:行转列

with t_test as(
  select 1 id, '张三' name, 70 score, 'CHINESE' subject from dual union all
  select 1 id, '张三' name, 90 score, 'MATH'    subject from dual union all
  select 1 id, '张三' name, 95 score, 'ENGLISH' subject from dual union all
  select 2 id, '李四' name, 75 score, 'CHINESE' subject from dual union all
  select 2 id, '李四' name, 85 score, 'MATH'    subject from dual union all
  select 2 id, '李四' name, 90 score, 'ENGLISH' subject from dual union all
  select 3 id, '王五' name, 90 score, 'CHINESE' subject from dual union all
  select 3 id, '王五' name, 90 score, 'MATH'    subject from dual union all
  select 3 id, '王五' name, 90 score, 'ENGLISH' subject from dual
)
select *
  from t_test-- 表别名无效!
 pivot (sum(score) -- 聚合函数
        for subject in('CHINESE' as 语文, 'MATH' as 数学, 'ENGLISH' as 英语))
 -- where id in (1, 2, 3)
 order by id;
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

测试结果:(细节:列的个数必须是确定的,如:语文、数学、英语)
在这里插入图片描述

2.2 unpivot:列转行

with t_test as (
  select 1 id, '张三' name, 70 chinese , 90 math , 95 english from dual union all
  select 2 id, '李四' name, 75 chinese , 85 math , 90 english from dual union all
  select 3 id, '王五' name, 90 chinese , 90 math , 90 english from dual
)
select id,
       name,
       score   成绩, -- 新增列
       subject 学科  -- 新增列
  from t_test -- 表别名无效!
 unpivot(score for subject in(chinese, math, english))
-- where id in (1, 2, 3)
 order by id;
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

测试结果:
在这里插入图片描述

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/凡人多烦事01/article/detail/675661
推荐阅读
相关标签
  

闽ICP备14008679号