DB2 row-to-column conversion is a common problem. The following describes how to implement row-to-column conversion in DB2. If you have encountered the problem of Row-to-column conversion in DB2, take a look.
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: S
ELECT 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
Implementation of Online DB2 backup
Four ways to delete DB2 data
Deep understanding of DB2 stored procedures
DB2 exception Processor type
How to Create a DB2 instance in Windows