create table ab(
姓名 varchar(10),
课程 varchar(10),
成绩类型 varchar2(10),
审核类型 varchar2(10),
分数 varchar2(10)
)
delete ab where 分数 = '47'
insert into ab values('张三','语文','补考','3','55');
insert into ab values('张三','语文','正考','3','54');
insert into ab values('张三','语文','重修','1','53');
insert into ab values('李四','语文','缓考','3','');
insert into ab values('王五','语文','免考','3','');
insert into ab values('刘六','语文','补考','3','');
insert into ab values('刘六','语文','正考','3','22');
select a.* from ab
pivot(SUM(分数) AS zcj, SUM(审核类型) AS shlx, MAX(成绩类型) AS lx FOR 成绩类型 IN('正考' AS sx, '补考' AS bk,'重修' AS cx , '免考' AS mk)) a
实际的效果:
按除了 分数 审核类型 成绩类型 这3个字段(用在pivot函数中的字段)的其他字段分组
其他函数必须为聚合函数:
分数 审核类型 成绩类型 (按成绩类型把 分数,审核类型(为值) 从行转成列)
补充(动态in):
方法1:
后台调取两次sql,先动态获取分组对象,再拼接sql再调取sql
如果要动态拼接in中的内容
比如:
String abc = ;
select listagg (cj, ',') WITHIN GROUP (ORDER BY cj) as cj from (
select ''''|| 成绩类型 ||''''|| ' AS ' || 成绩类型 as cj from ab group by 成绩类型
) a
在后台拼接sql后再调取,不能直接再in后面跟子句
String sql =
select a.* from ab
pivot(SUM(分数) AS zcj, SUM(审核类型) AS shlx, MAX(成绩类型) AS lx FOR 成绩类型
IN(“ + abc + ”)) a
方法2: 创建存储过程来调取
create or replace procedure p_test is
v_cjlx varchar2(2000);
v_sql varchar2(2000);
begin
select cj into v_cjlx from (
select listagg(cj, ',') WITHIN GROUP(ORDER BY cj) as cj
from (select '''' || 成绩类型 || '''' || ' AS ' || 成绩类型 as cj
from ab
group by 成绩类型) a
);
v_sql := 'select b.* from ab pivot(SUM(分数) AS zcj, SUM(审核类型) AS shlx, MAX(成绩类型) AS lx FOR 成绩类型 IN ('|| v_cjlx ||')) b ';
execute immediate v_sql;
dbms_output.put_line(v_sql);
end;