Row-to-Column
The following data is provided:
Create Table sales (Year int, quarter int, Results INT)
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
Expected results:
Year q1 q2 Q3 Q4
-------------------------------------------------------
2004 20 30 15 10
2005 18 40 12 27
This SQL statement can solve this problem:
Select Year,
Max (case when quarter = 1
Then results end) as Q1,
Max (case when quarter = 2
Then results end) as Q2,
Max (case when quarter = 3
Then results end) as Q3,
Max (case when quarter = 4
Then results end) as Q4
From sales
Group by year
Explain why you want to add Max, because without Max, the result is as follows:
Year q1 q2 Q3 Q4
-------------------------------------------------------
2004 20 ---
2004-30 --
2004--15-
2004---10
2005 18 ---
2005-40 --
2005--12-
2005---27
Column-to-row
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 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.