一、合并字段
原理:利用wm_concat函数、group by 分组函数完成
1、建立测试表
create table test_concat ( ID VARCHAR2(10), NAME VARCHAR2(20), TYPE VARCHAR2(10) )
2、初始化测试数据
ID NAME TYPE
1 jia 70
2 jia 75
3 jia 80
4 yi 75
5 yi 79
6 yi 88
3、执行sql
select name,wm_concat(type) type_all from test_concat group by name;
4、执行结果
NAME TYPE_ALL
jia 70,75,80
jia 70,75,80
jia 70,75,80
yi 75,79,88
yi 75,79,88
yi 75,79,88
5、这样执行完会出现重复数据,需要做去重操作。
二、行转列
原理:利用sum聚焦函数、decode判断函数、group by 分组函数来综合完成。
备注:sum函数聚焦的不仅可以是number的数值类型,还可以是非数值的varchar2类型等。
1、建立测试数据表:test
create table test ( ID VARCHAR2(10), NAME VARCHAR2(20), COURSE VARCHAR2(20), SCORE NUMBER )
2、初始化测试数据:
ID NAME COURSE SCORE
1 jia Chinese 70
2 jia Math 75
3 jia English 80
4 yi Chinese 75
5 yi Math 79
6 yi English 88
3、执行sql
select name, sum(decode(course,'Chinese',score,null)) Chinese, sum(decode(course,'Math',score,null)) Math, sum(decode(course,'English',score,null)) English from test group by name order by name;
或者将判断函数decode换成case when执行sql
select name, sum(case course when 'Chinese' then score else null end) Chinese, sum(case course when 'Math' then score else null end) Math, sum(case course when 'English' then score else null end) English from test group by name order by name;
4、执行结果:
NAME CHINESE MATH ENGLISH
jia 70 75 80
yi 75 79 88
三、行转列
原理:利用union函数
1、建立测试表
create table TEST_NEW ( ID VARCHAR2(10), NAME VARCHAR2(20), CHINESE VARCHAR2(10), ENGLISH VARCHAR2(10), MATH VARCHAR2(10) )
2、初始化测试数据
ID NAME CHINESE ENGLISH MATH
1 jia 70 75 80
2 yi 76 73 88
3、执行sql
select NAME, 'CHINESE' COURSE , CHINESE as SCORE from test_new union select NAME, 'MATH' COURSE, MATH as SCORE from test_new union select NAME, 'ENGLISH' COURSE, ENGLISH as SCORE from test_new order by NAME,COURSE
4、执行结果
NAME COURSE SCORE
jia Chinese 70
jia Math 75
jia English 80
yi Chinese 76
yi Math 73
yi English 88