Implementation of DB2 column-to-row

Source: Internet
Author: User

DB2 column-to-row is a common operation. The following describes the steps for column-to-row conversion in DB2. If you are interested in column-to-row conversion in DB2, take a look.

The following data is provided:

Create table salespartition
(Year INTEGER,
Q1 INTEGER,
Q2 INTEGER,
Q3 INTEGER,
Q4 INTEGER );
YEAR Q1 Q2 Q3 Q4
-------------------------------------------------------
2004 20 30 15 10
2005 18 40 12 27
Expected results
YEAR QUARTER RESULTS
---------------------------------
2004 1 20
2004 2 30
2004 3 15
2004 4 10
2005 1 18
2005 2 40
2005 3 12 2005 4 27
This SQL statement can be implemented:

Select s. Year, Q. Quarter, Q. Results
FROM salesclerk as s,
TABLE (VALUES (1, S. q1 ),
(2, S. q2 ),
(3, S. q3 ),
(4, S. q4 ))
As q (Quarter, Results );
The Data Types of the corresponding columns in each values must be the same, and the values can be arbitrary. For example, 1, 2, 3, and 4 are integer. The following describes the execution process: the core is to create a table using the table function, this table is a multi-row table implemented by value. An example of virtual table implemented by value is as follows:
Db2 => select * from (values (1, 2), (2, 3) as t1 (col1, col2)
COL1 COL2
----------------------
1 2
2 3
Two records are selected.
Db2 => select * from (values 1) as

1
-----------
1

1 record selected.

The difference is that a table in the from clause is related here, and a column in the table is taken as data.

Implementation of Online DB2 backup

How to Create a DB2 instance in Windows

DB2 Time Functions

DB2 common table expression usage

Four ways to delete DB2 data

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.