Oracle row-specific column Conversion

Source: Internet
Author: User

I. Implementation using SQL decode and PL/SQL Functions
1. Column and column conversion with fixed columns
For example

Student subject grade --------------------------- student1 language 80student1 mathematics 70student1 English 60student2 language 90student2 mathematics 80student2 English 100 ...... Convert to Chinese math English student1 80 70 60student2 90 80 100 ...... Statement: select student, sum (decode (subject, 'China', grade, null) "", sum (decode (subject, 'mat', grade, null )) "Mathematics", sum (decode (subject, 'English ', grade, null) "English" from tablegroup by student

2. Dynamic row-column conversion requires splicing of SQL statements through the Stored Procedure

For example:

CREATE OR REPLACE PROCEDURE GET_INSPECT_ITEM(    P_INSPECT_ID        IN VARCHAR2    ,Re_CURSOR           OUT SYS_REFCURSOR )AS  SQLSTR VARCHAR2 (4000);BEGIN   DECLARE   CURSOR C_CURSOR   IS   SELECT DISTINCT QCITEM_NAME     FROM REP_INSPECT_ITEM      WHERE INSPECT_ID=P_INSPECT_ID;    c_row C_CURSOR %ROWTYPE;    BEGIN             SQLSTR:='SELECT INSPECT_ID,SAMPLE_ID';              FOR c_row IN C_CURSOR LOOP              SQLSTR:=SQLSTR||', MAX(DECODE(T.QCITEM_NAME,''' ||c_row.QCITEM_NAME||''',T.VALUE,null)) AS "' || c_row.QCITEM_NAME || '"';              END LOOP;              SQLSTR:=SQLSTR||'FROM REP_INSPECT_ITEM T GROUP BY SAMPLE_ID,INSPECT_ID HAVING INSPECT_ID='||P_INSPECT_ID;              OPEN Re_CURSOR FOR SQLSTR ;   END;END GET_INSPECT_ITEM;

The result is as follows:


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.