Oracle row to column

1. Create a new table named TEST

2. Add data to the TEST table

INSERT INTO TEST(STUDENT,COURSE,SCORE)
select 'Zhang San','Language',78 from dual union
select 'Zhang San','Mathematics',87 from dual union
select 'Zhang San','English',82 from dual union
select 'Zhang San','Physics',90 from dual union
select 'Li Si','language',65 from dual union
select 'Li Si','Mathematics',77 from dual union
select 'Li Si','English',65 from dual union
select 'Li Si','Physics',85 from dual

The table data is as follows:

3. Column to row

Method ··1:

select
    Student,
    sum(decode(Course, 'math', Score)) math,
    sum(decode(Course, 'Physics', Score)) Physics,
    sum(decode(Course, 'English', Score)) English,
    sum(decode(Course, 'language', Score)) language
from
    TEST
group by Student

Note: If you add a fourth parameter to the decode() method. For example, decode(Course, 'Math', Score, -1) may cause problems when using sum in the outer layer. It is recommended to use max instead of sum.
Method 2:
select
    Student,
    sum(case Course when 'Math' then Score else null end) Math,
    sum(case Course when 'Physics' then Score else null end) Physics,
    sum(case Course when 'English' then Score else null end) English,
    sum(case Course when 'Chinese' then Score else null end) Chinese
from
    TEST
group by Student

The effect is as follows:


Note: sum means summation; for example, there are two Zhang Sans in the record, and the result displayed in the column-to-row display will be the sum of the results of the two Zhang Sans.

Reprinted from: http://www.cnblogs.com/Mr_JinRui/archive/2011/05/27/2060109.html

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327012259&siteId=291194637