1. 程式人生 > >行轉列,列轉行,圖一轉圖二或圖二轉圖一

行轉列,列轉行,圖一轉圖二或圖二轉圖一

col ont rom clas 轉行 chinese hang cor div

圖一:

Nam Course Score
zhangsan Chinese 85
zhangsan Maths 76
zhangsan English 80
lisi Chinese 82
lisi Maths 90
lisi English 55

圖二:

Nam Chinese Maths English
zhangsan 85 76 80
lisi 82 90 55

圖一轉圖二:

SELECT
    Nam,
    SUM(
        IF (Course = Chinese, Score, 0)
    ) Chinese,
    
SUM(IF(Course = Maths, Score, 0)) Maths, SUM( IF (Course = English, Score, 0) ) english FROM t GROUP BY Nam

圖二轉圖一:

(SELECT Nam, ChineseCourse, Chinese Score FROM t2)
UNION
(SELECT Nam, Maths Course , Maths Score FROM t2)
UNION
(SELECT Nam, English Course , English Score FROM
t2) ORDER BY Nam DESC

行轉列,列轉行,圖一轉圖二或圖二轉圖一