Oracle 行列转换函数pivot使用简介

Oracle 行列转换函数pivot使用简介

  • 关键函数pivot,其用法如下 pivot(聚合函数 for 列名 in(类型))
  • 新建一张数据库表
  • 插入数据后的表
  • 数据库查询行转列,使用case语句
  • 数据库查询行转列,使用decode语句
  • 数据库查询行转列,使用pivot语句
  • 数据库查询行转列,使用pivot语句(未筛选列的情况)

关键函数pivot,其用法如下 pivot(聚合函数 for 列名 in(类型))

语法示例:

select 
 * 
from table_name 
pivot( max(column_name01)                            --行转列后的列的值value,聚合函数是必须要有的
       for column_name02 in(value_1,value_2,value_3)     --需要行转列的列及其对应列的属性1/2/3
);

新建一张数据库表

建表语句:

-- Create table
create table T_STUDENT_SCORE
(
  ID             VARCHAR2(20) not null,
  STUDENT_NO     VARCHAR2(20),
  STUDENT_NAME   VARCHAR2(100),
  STUDENT_COURSE VARCHAR2(100),
  STUDENT_SCORE  NUMBER(5,2)
)
tablespace USERS;
-- Add comments to the table 
comment on table T_STUDENT_SCORE
  is '学生信息表';
-- Add comments to the columns 
comment on column T_STUDENT_SCORE.ID
  is '主键ID';
comment on column T_STUDENT_SCORE.STUDENT_NO
  is '学号';
comment on column T_STUDENT_SCORE.STUDENT_NAME
  is '姓名';
comment on column T_STUDENT_SCORE.STUDENT_COURSE
  is '课程';
comment on column T_STUDENT_SCORE.STUDENT_SCORE
  is '学分';
-- Create/Recreate primary, unique and foreign key constraints 
alter table T_STUDENT_SCORE
  add constraint PK_ID primary key (ID)
  using index 
  tablespace USERS
;

插入数据后的表

Oracle 行列转换函数pivot使用简介_第1张图片

数据库查询行转列,使用case语句

SQL语句:

select 
   student_no,
   max(case when student_course = '语文' then student_score end) 语文, 
   max(case when student_course = '数学' then student_score end) 数学, 
   max(case when student_course = '英语' then student_score end) 英语, 
   max(case when student_course = '物理' then student_score end) 物理, 
   sum(student_score) total 
from t_student_score
group by student_no;

数据库截图:
Oracle 行列转换函数pivot使用简介_第2张图片

数据库查询行转列,使用decode语句

SQL语句:

select 
   student_no, 
   max(decode(student_course, '语文', student_score)) 语文, 
   max(decode(student_course, '数学', student_score)) 数学, 
   max(decode(student_course, '英语', student_score)) 英语, 
   max(decode(student_course, '物理', student_score)) 物理, 
   sum(student_score) total 
from t_student_score
group by student_no;

数据库截图:

Oracle 行列转换函数pivot使用简介_第3张图片

数据库查询行转列,使用pivot语句

SQL语句:

-- 列转成行 pivot 【注意查询列】
SELECT 
 *
FROM (
 SELECT t.student_no, t.student_course, t.student_score FROM t_student_score t
) m
pivot ( max(student_score) for student_course in ('语文', '数学', '英语', '物理') );

数据库截图:

Oracle 行列转换函数pivot使用简介_第4张图片

数据库查询行转列,使用pivot语句(未筛选列的情况)

SQL语句:

-- 列转成行 pivot 【未筛选查询列】
SELECT 
 *
FROM t_student_score 
pivot ( max(student_score) for student_course in ('语文', '数学', '英语', '物理') );

数据库截图:

Oracle 行列转换函数pivot使用简介_第5张图片

你可能感兴趣的:(Java常用工具类,mysql,数据库)