先建个表吧~
create table kecheng
(
id NUMBER,
name VARCHAR2(20),
course VARCHAR2(20),
score NUMBER
);
insert into kecheng (id, name, course, score)
values (1, ‘张三’, ‘语文’, 67);
insert into kecheng (id, name, course, score)
values (1, ‘张三’, ‘数学’, 76);
insert into kecheng (id, name, course, score)
values (1, ‘张三’, ‘英语’, 43);
insert into kecheng (id, name, course, score)
values (1, ‘张三’, ‘历史’, 56);
insert into kecheng (id, name, course, score)
values (1, ‘张三’, ‘化学’, 11);
insert into kecheng (id, name, course, score)
values (2, ‘李四’, ‘语文’, 54);
insert into kecheng (id, name, course, score)
values (2, ‘李四’, ‘数学’, 81);
insert into kecheng (id, name, course, score)
values (2, ‘李四’, ‘英语’, 64);
insert into kecheng (id, name, course, score)
values (2, ‘李四’, ‘历史’, 93);
insert into kecheng (id, name, course, score)
values (2, ‘李四’, ‘化学’, 27);
insert into kecheng (id, name, course, score)
values (3, ‘王五’, ‘语文’, 24);
insert into kecheng (id, name, course, score)
values (3, ‘王五’, ‘数学’, 25);
insert into kecheng (id, name, course, score)
values (3, ‘王五’, ‘英语’, 8);
insert into kecheng (id, name, course, score)
values (3, ‘王五’, ‘历史’, 45);
insert into kecheng (id, name, course, score)
values (3, ‘王五’, ‘化学’, 1);
commit;
1.Decode方式(固定列)
介绍下decode()函数decode(A,’B’,C,’D’)
如果A为B就把A替换成C否则显示D
SELECT ID,NAME,
SUM(DECODE(course,’语文’,score,0)) 语文,–这里使用max,min都可以~
SUM(DECODE(course,’数学’,score,0)) 数学,
SUM(DECODE(course,’英语’,score,0)) 英语,
SUM(DECODE(course,’历史’,score,0)) 历史,
SUM(DECODE(course,’化学’,score,0)) 化学
FROM kecheng GROUP BY ID ,NAME
2.Case方式
Case when A=B then C else D end
当A等于B的时候,A显示为C否则显示D
SELECT ID,NAME,
MAX(CASE WHEN course = ‘语文’ THEN score ELSE 0 END) 语文,
MAX(CASE WHEN course = ‘英语’ THEN score ELSE 0 END) 英语,
MAX(CASE WHEN course = ‘历史’ THEN score ELSE 0 END) 历史,
MAX(CASE WHEN course = ‘数学’ THEN score ELSE 0 END) 数学,
MAX(CASE WHEN course = ‘化学’ THEN score ELSE 0 END) 化学
FROM kecheng GROUP BY ID,NAME
输出结果跟上方相同的
3.wmsys.wm_concat行列转换函数
这玩意儿的前世今生,想必大多人都知道
想当年,在我们需要将某字段多行内容拼接起来的时候,wm_concat提供了很好的方法
这使得这个未公开的函数,得到了广泛的宣传与运用
但是,不公开,英文是undocumented,就意味着随时可能发生变更
这不,10.2.0.5上,其返回类型从varchar2变为了clob
而在12c当中,干脆就取消了此函数,这个函数不能用也是正常的,会提示标识符无效~
SELECT ID,NAME,wm_concat(course || ‘:’||score) a FROM kecheng GROUP BY ID ,NAME;