PL/SQL converts rows and columns

Source: Internet
Author: User
Tags table definition


PL/SQL converts rows and columns. In this blog post, we write a simple conversion of rows and columns. Here is a specific example. Some people have asked related questions on the Forum before. Many of the answers mentioned above are feasible. Of course, they think that they are very high-end, but they have no answer. Next, go to the topic. Www.2cto.com part1: column-to-row. Requirement: The following table is provided in the example:

The table definition is as follows: create table TEST_TB_GRADE (id number (10) not null, USER_NAME VARCHAR2 (20 CHAR), COURSE VARCHAR2 (20 CHAR), score float) requires conversion:

The following is a feasible PL/SQL statement: www.2cto.com select t. user_name as name, sum (decode (t. course, 'China', score, null) as language, sum (decode (t. course, 'mat', score, null) as mathematics, sum (decode (t. course, 'English ', score, null) as English from test_tb_grade t group by t. user_name order by t. the implementation result of user_name is shown in the requirement.

Part2: Convert rows to columns. Requirement: The following table is provided in the example.

The table structure is as follows: create table TEST_TB_GRADE2 (id number (10) not null, USER_NAME VARCHAR2 (20 CHAR), CN_SCORE FLOAT, MATH_SCORE FLOAT, EN_SCORE FLOAT) needs to be converted to the following form: www.2cto.com

The following is an executable PL/SQL statement: select user_name, 'China' as COURSE, CN_SCORE as SCORE from test_tb_grade2 union allselect user_name, 'mate' as COURSE, MATH_SCORE as SCORE from test_tb_grade2 union allselect user_name, 'English 'as COURSE, EN_SCORE as SCORE from test_tb_grade2 order by user_name. The COURSE implementation result is shown in the requirement.

Author: DebugLZQ

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.