mysql中sql行列轉換


1.列轉行

select class_id,MAX(CASE kemu when '語文' then score ELSE 0 end)as '語文' ,
MAX(CASE kemu when '數學' then score ELSE 0 end)as '數學' ,
MAX(CASE kemu when '英語' then score ELSE 0 end)as '英語'
FROM scoreinfo GROUP BY stuent_id

 

 2.依據查詢的結果機創建一個新表

CREATE table pei_new (select class_id,MAX(CASE kemu when '語文' then score ELSE 0 end)as '語文' ,
MAX(CASE kemu when '數學' then score ELSE 0 end)as '數學' ,
MAX(CASE kemu when '英語' then score ELSE 0 end)as '英語'
FROM scoreinfo GROUP BY stuent_id)

 

 3.復制一張表 ,只復制表結構

CREATE table pei_new like scoreinfo;

4.行轉列

 

 

 

SELECT class_id,'語文' as 科目,語文 as 成績 FROM pei_new
UNION
SELECT class_id,'數學',數學 FROM pei_new
union
SELECT class_id,'英語',英語 FROM pei_new


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM