存在表score,記錄學生的考試成績,如下圖所示:
現要求以 學生姓名,語文,數學,英語 這種格式顯示學生成績,如下圖所示
具體步驟如下:
1、首先,使用case when函數輸出單個課程的成績
case when course='語文' then score end as 語文 case when course='數學' then score end as 數學 case when course='英語' then score end as 英語
sql語句:
select name ,case when course='語文' then score end as 語文, case when course='數學' then score end as 數學, case when course='英語' then score end as 英語 from score;
輸出結果如下圖所示:
2、使用group by 和sum,去掉NULL得出課程的成績
sql語句:
select name ,sum(case when course='語文' then score end) as 語文, sum(case when course='數學' then score end )as 數學, sum(case when course='英語' then score end )as 英語 from score group by name;
輸出結果如下圖所示
就得出行轉列的輸出結果了
總結:在具體的生活場景中,使用學生姓名,課程1,課程2,課程3……的表結構是不太合理的,比如選修課,不可能每個學生都選一樣的課程,這種結構會存在浪費存儲空間的情況,比較好的做法就是一行表示一個學生的某個課程的成績,再使用行轉列方法輸出想要的成績結構。