DB2 行列轉置之行轉列
構造表和資料
CREATE TABLE Sales(Year INTEGER,Quarter INTEGER,Results INTEGER);
insert into sales values(2005,4,27);
insert into sales values(2005,3,12);
insert into sales values(2005,2,40);
insert into sales values(2005,1,18);
insert into sales values(2004,4,10);
insert into sales values(2004,3,15);
insert into sales values(2004,2,30);
insert into sales values(2004,1,20);
select * from sales order by year,quarter
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
如果想轉換成下面的樣子
YEAR Q1 Q2 Q3 Q4
---- -- -- -- --
2004 20 30 15 10
2005 18 40 12 27
轉換SQL
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
CREATE TABLE Sales(Year INTEGER,Quarter INTEGER,Results INTEGER);
insert into sales values(2005,4,27);
insert into sales values(2005,3,12);
insert into sales values(2005,2,40);
insert into sales values(2005,1,18);
insert into sales values(2004,4,10);
insert into sales values(2004,3,15);
insert into sales values(2004,2,30);
insert into sales values(2004,1,20);
select * from sales order by year,quarter
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
如果想轉換成下面的樣子
YEAR Q1 Q2 Q3 Q4
---- -- -- -- --
2004 20 30 15 10
2005 18 40 12 27
轉換SQL
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
來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/725820/viewspace-2132493/,如需轉載,請註明出處,否則將追究法律責任。
相關文章
- DB2行列轉置之行轉列DB2
- excel列轉行怎麼做 excel如何轉置行列Excel
- oracle行列轉換-行轉列Oracle
- oracle行列轉換-列轉行Oracle
- 行列轉換,列行轉換統計
- sql行列轉置的實現方法SQL
- oracle行列轉換-字串轉換成多列Oracle字串
- oracle行列轉換-多列轉換成字串Oracle字串
- 一個sql的行列轉置的例子SQL
- SQL 如何實現動態的行列轉置SQL
- postgresql高階應用之行轉列&彙總求和SQL
- 行列轉換
- 行列轉換 交叉表 (轉)
- 使用動態SQL語句實現簡單的行列轉置(動態產生列)SQL
- Kettle行列轉換
- 偽行列轉換!
- 行列轉換sqlSQL
- Oracle-行列轉換Oracle
- MySQL行列轉換拼接MySql
- 行列轉換之大全~~~
- sql server 行列轉換SQLServer
- oracle行列轉換-多行轉換成字串Oracle字串
- DB2 SQL之行合併(連線)DB2SQL
- mysql行列轉換詳解MySql
- sql server行列轉換案例SQLServer
- Oracle 行列轉換 經典Oracle
- Oracle 行列轉換總結Oracle
- Oracle 行列轉換小結Oracle
- 【SQL 學習】行列轉換SQL
- 【SQL】行列轉換方法示例SQL
- Oracle行列轉換總結Oracle
- Shell練習 行列轉換
- 複雜的行列轉換
- SQL Server資料庫基礎之行資料轉換為列資料SQLServer資料庫
- 專訪:Ubuntu Linux源自太空之行(轉)UbuntuLinux
- 記錄一個行列轉換
- 通用的行列轉換的方法
- 行列轉換問題總結