各位前輩們好
我是剛學習資訊工程的超級菜鳥
想在這邊詢問我寫sql遇到的難關~
目前再幫公司整理資料庫資料統計成月報表
整理出來的型態長下列這樣(此資料內容適用 month() 搜集出來的):
month | useMins | sumCase | sumPer |sumChat | sumRating
6 | 42 | 38 | 2 | 200 | 798
7 | 0 | 7 | 1 | 2 | 5
但我需要的型態為這樣:
name | 01 | 02 | 03 | 04 | 05 | 06 | 07 | 08 | 09 | 10 | 11 |12
useMins | 0 | 0 | 0 | 0 | 0 | 42 | 0 | 0 | 0 | 0 | 0 | 0
sumCase | 0 | 0 | 0 | 0 | 0 | 38 | 7 | 0 | 0 | 0 | 0 | 0
sumPer | 0 | 0 | 0 | 0 | 0 | 2 | 1 | 0 | 0 | 0 | 0 | 0
sumChat | 0 | 0 | 0 | 0 | 0 | 200| 2 | 0 | 0 | 0 | 0 | 0
sumRating | 0 | 0 | 0 | 0 | 0 | 798| 5 | 0 | 0 | 0 | 0 | 0
一般網路上查的行列轉換
最後都還會有一列是無法轉換的
但我需要全部都轉換且能新增一列名為name的欄位
請問大神們有什麼方法可以做到嗎?
CREATE TABLE TableA(
month varchar(20),
useMins int(20),
sumCase int(20),
sumPer int(20),
sumChat int(20),
sumRating int(20)
);
INSERT INTO TableA (month,useMins,sumCase,sumPer,sumChat,sumRating)
VALUES
('6',42,38,2,200,798),
('7',0,7,1,2,5);
SELECT name,
SUM(CASE WHEN month='1' THEN amount ELSE 0 END) AS '01',
SUM(CASE WHEN month='2' THEN amount ELSE 0 END) AS '02',
SUM(CASE WHEN month='3' THEN amount ELSE 0 END) AS '03',
SUM(CASE WHEN month='4' THEN amount ELSE 0 END) AS '04',
SUM(CASE WHEN month='5' THEN amount ELSE 0 END) AS '05',
SUM(CASE WHEN month='6' THEN amount ELSE 0 END) AS '06',
SUM(CASE WHEN month='7' THEN amount ELSE 0 END) AS '07',
SUM(CASE WHEN month='8' THEN amount ELSE 0 END) AS '08',
SUM(CASE WHEN month='9' THEN amount ELSE 0 END) AS '09',
SUM(CASE WHEN month='10' THEN amount ELSE 0 END) AS '10',
SUM(CASE WHEN month='11' THEN amount ELSE 0 END) AS '11',
SUM(CASE WHEN month='12' THEN amount ELSE 0 END) AS '12'
FROM (
SELECT month,'useMins' AS name,useMins AS amount
FROM TableA
UNION ALL
SELECT month,'sumCase' AS name,sumCase AS amount
FROM TableA
UNION ALL
SELECT month,'sumPer' AS name,sumPer AS amount
FROM TableA
UNION ALL
SELECT month,'sumChat' AS name,sumChat AS amount
FROM TableA
UNION ALL
SELECT month,'sumRating' AS name,sumRating AS amount
FROM TableA
) AS Z
GROUP BY name
ORDER BY CASE WHEN name='useMins' THEN 1
WHEN name='sumCase' THEN 2
WHEN name='sumPer' THEN 3
WHEN name='sumChat' THEN 4
WHEN name='sumRating' THEN 5 ELSE 10 END