MySQL中,有時需要將行轉(zhuǎn)列或者列轉(zhuǎn)行,實現(xiàn)這些操作的方法有很多,比如使用CASE語句、GROUP_CONCAT函數(shù)和UNION操作等。
下面以實例來說明:
-- 行轉(zhuǎn)列 SELECT student_id, MAX(CASE WHEN subject = '語文' THEN score ELSE NULL END) AS chinese, MAX(CASE WHEN subject = '數(shù)學' 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; -- 列轉(zhuǎn)行 SELECT student_id, '語文' AS subject, chinese AS score FROM score_tb UNION ALL SELECT student_id, '數(shù)學' AS subject, math AS score FROM score_tb UNION ALL SELECT student_id, '英語' AS subject, english AS score FROM score_tb;
以上就是MySQL中行轉(zhuǎn)列和列轉(zhuǎn)行的兩種實現(xiàn)方式,通過相應(yīng)的方法,我們可以比較輕松地實現(xiàn)這些操作。