MySQL中,有時需要將行轉列或者列轉行,實現這些操作的方法有很多,比如使用CASE語句、GROUP_CONCAT函數和UNION操作等。
下面以實例來說明:
-- 行轉列 SELECT student_id, MAX(CASE WHEN subject = '語文' THEN score ELSE NULL END) AS chinese, MAX(CASE WHEN subject = '數學' THEN score ELSE NULL END) AS math, MAX(CASE WHEN subject = '英語' THEN score ELSE NULL END) AS english FROM score_tb GROUP BY student_id; -- 列轉行 SELECT student_id, '語文' AS subject, chinese AS score FROM score_tb UNION ALL SELECT student_id, '數學' AS subject, math AS score FROM score_tb UNION ALL SELECT student_id, '英語' AS subject, english AS score FROM score_tb;
以上就是MySQL中行轉列和列轉行的兩種實現方式,通過相應的方法,我們可以比較輕松地實現這些操作。
上一篇mysql 行轉列查詢
下一篇丑化的css文件轉化不了