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

1)、創建資料表并添加資料
create table Score ( 學號 nvarchar(10) ,課程 nvarchar(10) ,成績 nvarchar(10) ); insert into Score(學號,課程,成績)values('0001','語文',87),('0001','數學',79),('0001','英語',95) ,('0002','語文',69),('0002','數學',84);
2)、先查詢觀察整張表的結構
select * from Score;

3)、先顯示要展示的基本的結構
select 學號,'語文','數學','英語' from Score;

4)、使用case陳述句,如果課程=語文 則直接顯示語文成績,否則顯示0,其他科目同
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行,使用分組聚合(按學號分組,各科分組聚合)
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 學號;

轉載請註明出處,本文鏈接:https://www.uj5u.com/net/2948.html
標籤:ASP.NET
