欧美一区二区三区,国内熟女精品熟女A片视频小说,日本av网,小鲜肉男男GAY做受XXX网站

mysql 行轉列轉行

錢良釵1年前6瀏覽0評論

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中行轉列和列轉行的兩種實現方式,通過相應的方法,我們可以比較輕松地實現這些操作。