表的透視變換

將表的行列倒置顯示(透視變換)spa

1)、建立數據表並添加數據code

create table Score
(
    學號 nvarchar(10)
    ,課程 nvarchar(10)
    ,成績 nvarchar(10)
);
insert into Score(學號,課程,成績)values('0001','語文',87),('0001','數學',79),('0001','英語',95)
,('0002','語文',69),('0002','數學',84);

2)、先查詢觀察整張表的結構blog

select * from Score;

 

 3)、先顯示要展現的基本的結構數學

select 學號,'語文','數學','英語'  from Score;

 

 4)、使用case語句,若是課程=語文 則直接顯示語文成績,不然顯示0,其餘科目同table

select 學號
    ,case when 課程='語文' then 成績 else 0 end as'語文'
    ,case when 課程='數學' then 成績 else 0 end as'數學'
    ,case when 課程='英語' then 成績 else 0 end as'英語'
from Score;

 

 5)、從5行變2行,使用分組聚合(按學號分組,各科分組聚合)class

select 學號
    ,sum(case when 課程='語文' then 成績 else 0 end) as'語文'
    ,sum(case when 課程='數學' then 成績 else 0 end) as'數學'
    ,sum(case when 課程='英語' then 成績 else 0 end) as'英語'
from Score group by 學號;

相關文章
相關標籤/搜索
本站公眾號
   歡迎關注本站公眾號,獲取更多信息