1. Merge fields
Principle: Use wm_concat function, group by grouping function to complete
1. Create a test table
create table test_concat ( ID VARCHAR2(10), NAME VARCHAR2(20), TYPE VARCHAR2(10) )
2. Initialize the test data
ID NAME TYPE
1 jia 70
2 jia 75
3 jia 80
4 yi 75
5 yi 79
6 yi 88
3. Execute sql
select name,wm_concat(type) type_all from test_concat group by name;
4. Execution results
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. After this execution, there will be duplicate data, which needs to be deduplicated.
Two, row to column
Principle: Use the sum focus function, the decode judgment function, and the group by grouping function to complete the synthesis.
Note: The sum function can focus not only on the numeric type of number, but also on the non-numeric varchar2 type.
1. Create a test data table: test
create table test ( ID VARCHAR2(10), NAME VARCHAR2(20), COURSE VARCHAR2(20), SCORE NUMBER )
2. Initialize the test data:
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. Execute 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;
Or replace the judgment function decode with case when executing 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. Execution result:
NAME CHINESE MATH ENGLISH
Jia 70 75 80
yi 75 79 88
Three, row to column
Principle: use the union function
1. Create a test table
create table TEST_NEW ( ID VARCHAR2(10), NAME VARCHAR2(20), CHINESE VARCHAR2(10), ENGLISH VARCHAR2(10), MATH VARCHAR2(10) )
2. Initialize the test data
ID NAME CHINESE ENGLISH MATH
1 jia 70 75 80
2 yi 76 73 88
3. Execute 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. Execution results
NAME COURSE SCORE
jia Chinese 70
jia Math 75
jia English 80
yi Chinese 76
yi Math 73
yi English 88