zoukankan      html  css  js  c++  java
  • 行列转置(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

    结果集如下:

  • 相关阅读:
    可以在Android上发定时短信
    Java的网络编程初识
    字节流与字符流的区别
    JAVA中的反射机制详解
    C语言C++语言中静态变量和静态函数
    Android网络编程
    C++中const用法总结
    Java中IO操作的基本规律
    面试智力题 (附答案)
    Java网络编程(总结)
  • 原文地址:https://www.cnblogs.com/chinas/p/6234587.html
Copyright © 2011-2022 走看看