MySQL 資料透視:將列轉換為行
在 MySQL 等關聯式資料庫中,為了報表目的,常常需要轉換資料。其中一種轉換涉及將列轉換為行,這個過程稱為「透視」。此技術允許更靈活和更簡潔的數據表示。
問題:
考慮以下 MySQL 表:
CREATE TABLE mytable ( id INT, month VARCHAR(3), col1 VARCHAR(1), col2 VARCHAR(1), col3 VARCHAR(1), col4 VARCHAR(1) ); INSERT INTO mytable (id, month, col1, col2, col3, col4) VALUES (101, 'Jan', 'A', 'B', NULL, 'B'), (102, 'Feb', 'C', 'A', 'G', 'E');
目標是建立一個報表,將 col1 到 col4 的值作為行顯示,月份 Jan 和 Feb 作為列。
解:
MySQL 沒有提供用於反透視或透視資料的內建函數。但是,我們可以使用 UNION ALL 和帶有 CASE 表達式的聚合來模擬這些操作。
1. 反透視:
為了反透視數據,我們建立一個新的子查詢,使用 UNION ALL 將所有欄位中的行組合到單一欄位中:
SELECT id, month, col1 AS `value`, 'col1' AS `descrip` UNION ALL SELECT id, month, col2 AS `value`, 'col2' AS `descrip` UNION ALL SELECT id, month, col3 AS `value`, 'col3' AS `descrip` UNION ALL SELECT id, month, col4 AS `value`, 'col4' AS `descrip` FROM mytable;
2. 透視:
接下來,我們將反透視查詢包裝在一個子查詢中,並使用聚合和 CASE 語句將資料轉換為所需的格式:
SELECT descrip, MAX(CASE WHEN month = 'Jan' THEN `value` ELSE NULL END) AS Jan, MAX(CASE WHEN month = 'Feb' THEN `value` ELSE NULL END) AS Feb FROM ( SELECT id, month, `value`, descrip FROM ( SELECT id, month, col1 AS `value`, 'col1' AS `descrip` UNION ALL SELECT id, month, col2 AS `value`, 'col2' AS `descrip` UNION ALL SELECT id, month, col3 AS `value`, 'col3' AS `descrip` UNION ALL SELECT id, month, col4 AS `value`, 'col4' AS `descrip` FROM mytable ) AS unpivoted ) AS src GROUP BY descrip;
結果:
Descrip | Jan | Feb |
---|---|---|
col1 | A | C |
col2 | B | A |
col3 | NULL | G |
col4 | B | E |
注意:將 ELSE 0 END
改為 ELSE NULL END
,使結果更符合資料庫的規範,避免出現不必要的0值。
以上是如何在 MySQL 中將列轉換為行以進行報告?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

todropaviewInmySQL,使用“ dropviewifexistsview_name;” andTomodifyAview,使用“ createOrreplaceViewViewViewview_nameAsSelect ...”。 whendroppingaview,asew dectivectenciesanduse和showcreateateviewViewview_name;“ tounderStanditSsstructure.whenModifying

mySqlViewScaneFectectialized unizedesignpatternslikeadapter,Decorator,Factory,andObserver.1)adapterPatternadaptSdataForomDifferentTablesIntoAunifiendView.2)decoratorPatternenhancateDataWithCalcalcualdCalcalculenfields.3)fieldfields.3)

查看InMysqlareBeneForsImplifyingComplexqueries,增強安全性,確保dataConsistency,andOptimizingPerformance.1)他們simimplifycomplexqueriesbleiesbyEncapsbyEnculatingThemintoreusableviews.2)viewsEnenenhancesecuritybyControllityByControllingDataAcces.3)

toCreateAsimpleViewInmySQL,USEthecReateaTeviewStatement.1)defitEtheetEtheTeViewWithCreatEaTeviewView_nameas.2)指定usethectstatementTorivedesireddata.3)usethectStatementTorivedesireddata.3)usetheviewlikeatlikeatlikeatlikeatlikeatlikeatable.views.viewssimplplifefifydataaccessandenenanceberity but consisterfort,butconserfort,consoncontorfinft

1)foralocaluser:createUser'localuser'@'@'localhost'Indidendify'securepassword'; 2)foraremoteuser:creationuser's creationuser'Remoteer'Remoteer'Remoteer'Remoteer'Remoteer'Remoteer'Remoteer'Remoteer'Rocaluser'@'localhost'Indidendify'seceledify'Securepassword'; 2)

mysqlviewshavelimitations:1)他們不使用Supportallsqloperations,限制DatamanipulationThroughViewSwithJoinsOrsubqueries.2)他們canimpactperformance,尤其是withcomplexcomplexclexeriesorlargedatasets.3)

porthusermanagementinmysqliscialforenhancingsEcurityAndsingsmenting效率databaseoperation.1)usecReateusertoAddusers,指定connectionsourcewith@'localhost'or@'%'。

mysqldoes notimposeahardlimitontriggers,butacticalfactorsdeterminetheireffactective:1)serverConfiguration impactactStriggerGermanagement; 2)複雜的TriggerSincreaseSySystemsystem load; 3)largertablesslowtriggerperfermance; 4)highConconcConcrencerCancancancancanceTigrignecentign; 5); 5)


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

SublimeText3 Linux新版
SublimeText3 Linux最新版

SublimeText3 英文版
推薦:為Win版本,支援程式碼提示!

記事本++7.3.1
好用且免費的程式碼編輯器

PhpStorm Mac 版本
最新(2018.2.1 )專業的PHP整合開發工具

Safe Exam Browser
Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。