Statement of Oracle row-to-column Conversion

Source: Internet
Author: User

Statement for Oracle row-to-column conversion:

/*

Drop table foo;

*/

/** Create a demo table **/

Create table foo (

Bbbid number (2), -- primary key

Depid number (2), -- unit NUMBER

AAC006 VARCHAR2 (1) -- Gender 1 male 2 female 0 unknown

CONSTRAINT CK_AAC006 CHECK (AAC006 = '1' OR AAC006 = '2' OR AAC006 = '0 ')

);

/** Insert data for testing **/

Insert into foo values (1, 1, '1 ');

Insert into foo values (2, 1, '0 ');

Insert into foo values (3,1, '2 ');

Insert into foo values (4,1, '2 ');

Insert into foo values (5, 2, '1 ');

Insert into foo values (6, 2, '0 ');

Insert into foo values (7,2, '2 ');

Insert into foo values (8, 2, '2 ');

Insert into foo values (9, 3, '2 ');

Insert into foo values (10, 3, '2 ');

Insert into foo values (11,3, '2 ');

/**

Objective: To perform row-to-column conversion on the table, you need to obtain the following result set:

Unknown depid male and female

1 1  1 2

2 1  1 2

3 0  0 3

*/

/** Raw data **/

SELECT * from foo;

/** Convert FOO. AAC006 to a value after three columns based on the value of the gender code table **/

Select depid,

DECODE (AAC006, '0', 1, 0) "male ",

DECODE (AAC006, '1', 1, 0) "female ",

DECODE (AAC006, '2', 1, 0) "unknown"

From foo;

/** Perform processing on the previous result set to get the row-to-column conversion result! **/

Select depid,

SUM (DECODE (AAC006, '0', 1, 0) "male ",

SUM (DECODE (AAC006, '1', 1, 0) "female ",

SUM (DECODE (AAC006, '2', 1, 0) "unknown"

FROM FOO

Group by depid;


/**

Summary (czw 20120624 ):

Row-to-column splitting refers to splitting a field into several fields according to the code value,Finally, the clustering function is used to obtain the corresponding value.

**/

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.