Oracle Data Display horizontal table to vertical table

Source: Internet
Author: User

1. Create a table
Copy codeThe Code is as follows:
-- Create table
Create table test
(
Dm1 char (3 ),
Dm2 char (3 ),
Mc1 nvarchar2 (20 ),
Val nvarchar2 (20)
)

2. Fill in the following data:

DM1 DM2 MC1 VAL
101 1 C1 100
101 1 C2 80
101 1 C3 40
101 2 C1 30
101 2 C2 80
102 4 C1 9
102 6 C2 50

The converted data is shown as follows:

DM1 DM2 C1 C2 C3
101 1 100 80 40
101 2 30 80  
102 4 9    
102 6   50  

3. Conversion statement:
Copy codeThe Code is as follows:
Select dm1, dm2, sum (decode (mc1, 'c1', val) c1, sum (decode (mc1, 'c1', val) c2, sum (decode (mc1, 'c3', val) c3
From test
Group by dm1, dm2

Note: This statement is executed when val is a numeric value. If val is not numeric or contains a string or other types, an error is returned when sum is used, here we can use another method to change sum to max. The statement is as follows:
Copy codeThe Code is as follows:
Select dm1, dm2, max (decode (mc1, 'c1', val) c1, max (decode (mc1, 'c1', val) c2, max (decode (mc1, 'c3', val) c3
From test
Group by dm1, dm2

In addition, the horizontal table to the vertical table can also be implemented using a case statement similar to decode. The principle is the same as that of this statement, which is not described too much here.

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.