Oracle vertical table to horizontal table

Source: Internet
Author: User

Assume that the following vertical table exists. The first column is the ID of a business data, the second column is the type, and the third column is the value corresponding to the type, for example:

As shown in the preceding table, there are three types: 2, 3, and 4. The three types of business data Id 1 have values, and the three types of business data ID 2 have values, if the business data ID is 3, only Type 2 and 3 have values. to display the vertical table horizontally, you can use the followingCode:

-- ===================================================== =============================-- Change the vertical table to a horizontal table: -- 1. conversion type. The type value must be an integer and not equal to 0. That is, 0 is meaningless, 0 can be expressed as null -- ============================================ ===================================== select T. ID, sum (decode (T. code, 2, 2, 0) "second", -- if the row type is 2, it is 2, and the others are 0 sum (decode (T. code, 3, 3, 0) "third item", sum (decode (T. code, 4, 4, 0) "fourth item" from TTT t where T. id = 1 group by T. ID; -- ===================================================== =============================-- change the vertical table to a horizontal table: -- 1. the data corresponding to the conversion type, and the data must be a numerical value, and 0 is meaningless, that is, 0 can be expressed as null -- ==================================== ======================================= select T. ID, sum (decode (T. code, 2, T. val, 0) "second", -- if the row type is 2, the decode value corresponding to type 2 is displayed; otherwise, the value 0 sum (decode (T. code, 3, T. val, 0) "third", sum (decode (T. code, 4, T. val, 0) "fourth" from ttt t group by T. ID;

 

 

 

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.