• 行列转置(Oracle)


    行列转换的几种形式

      行列转换包含如下几种形式:行转列、列转行、多列转换成字符串、多行转换成字符串、字符串转换成多列、字符串转换成多行

    一、Oracle行列转置

    1、行转列

     (1)创建表格、插入测试数据

    create table student(
           id number,
           name varchar2(20),
           course varchar2(20),
           score number
    )

    插入测试数据,如下:

    (2)方法一:使用wm_concat()函数

    select id, name, wm_concat(score) scores from student group by id, name;

    结果集如下:      

    (3)方法二:使用decode()函数

    select id,name,sum(decode(course,'Chinese',score,null)) "Chinese",
                   sum(decode(course,'Math',score,null)) "Math",
                   sum(decode(course,'English',score,null)) "English"
           from student
           group by id,name

    结果集如下:

    (4)方法三:使用case表达式

    select id,name,sum(case when course='Chinese' then score end) "Chinese",
                   sum(case when course='Math' then score end) "Math",
                   sum(case when course='English' then score end) "English"
    from student
    group by id,name

    结果集如下:

    2、列转行

    (1)建表

    使用上面的查询结果:

    create table scores as
    select id,name,sum(case when course='Chinese' then score end) "Chinese",
                   sum(case when course='Math' then score end) "Math",
                   sum(case when course='English' then score end) "English"
    from student
    group by id,name
    order by i

    得到表及记录如下:

    (2)方法一:合并查询union

    select id,name,'Chinese' as course from scores
    union
    select id,name,'Math' as course from scores
    union
    select id,name,'English' as course from scores

    结果集如下:

  • 相关阅读:
    【大数据面试之对线面试官】MapReduce/HDFS/YARN面试题70连击
    2021年最新版大数据面试题全面总结-持续更新
    Hbase性能优化百科全书
    【大数据面试题】Flink第一弹60连发
    DockerFile
    Docker容器数据卷
    Docker入门
    八、Sentinel服务保护框架
    七、Gateway高可用集群与动态网关
    五、Nacos集群部署实现原理
  • 原文地址:https://www.cnblogs.com/chinas/p/6234587.html
Copyright © 2020-2023  润新知