根據你描述,我覺得額,你可能是想知道,行如何轉列,列如何轉行吧。
表如下:
(1)行轉列(利用最大值)
select user_name,
MAX(CASE WHEN course="語文" THEN score ELSE 0 END) 語文,
MAX(CASE WHEN course="英語" THEN score ELSE 0 END) 英語,
MAX(CASE WHEN course="數學" THEN score ELSE 0 END) 數學
from rows_test GROUP BY user_name
(2)行轉列(利用sum總和)
SUM(CASE WHEN course="語文" THEN score ELSE 0 END) 語文,
SUM(CASE WHEN course="英語" THEN score ELSE 0 END) 英語,
SUM(CASE WHEN course="數學" THEN score ELSE 0 END) 數學
(3)行轉列(行合併)
select user_name,GROUP_CONCAT(course,":",score) from rows_test GROUP BY user_name
select user_name, "英語" COURSE , EN_SCORE as SCORE from column_test
union select user_name, "語文" COURSE, CN_SCORE as SCORE from column_test
union select user_name, "數學" COURSE, MATH_SCORE as SCORE from column_test
order by user_name,COURSE;
整理了一個比較簡單的案例方法,學到了嗎?
根據你描述,我覺得額,你可能是想知道,行如何轉列,列如何轉行吧。
行轉列表如下:
(1)行轉列(利用最大值)
select user_name,
MAX(CASE WHEN course="語文" THEN score ELSE 0 END) 語文,
MAX(CASE WHEN course="英語" THEN score ELSE 0 END) 英語,
MAX(CASE WHEN course="數學" THEN score ELSE 0 END) 數學
from rows_test GROUP BY user_name
(2)行轉列(利用sum總和)
select user_name,
SUM(CASE WHEN course="語文" THEN score ELSE 0 END) 語文,
SUM(CASE WHEN course="英語" THEN score ELSE 0 END) 英語,
SUM(CASE WHEN course="數學" THEN score ELSE 0 END) 數學
from rows_test GROUP BY user_name
(3)行轉列(行合併)
select user_name,GROUP_CONCAT(course,":",score) from rows_test GROUP BY user_name
列轉行select user_name, "英語" COURSE , EN_SCORE as SCORE from column_test
union select user_name, "語文" COURSE, CN_SCORE as SCORE from column_test
union select user_name, "數學" COURSE, MATH_SCORE as SCORE from column_test
order by user_name,COURSE;
整理了一個比較簡單的案例方法,學到了嗎?