SQL錶行列轉換後再計算排名

行列轉換後再加一個總分列,名次列

select st.StuNo, name as 姓名 ,
max(case course when '語文' then score else 0 end) 語文,
max(case course when '數學' then score else 0 end) 數學,
max(case course when '物理' then score else 0 end) 物理,
sum(score) as 總分,
RANK() OVER(ORDER BY sum(score)desc)  as 名次
from Student as st,Score as sc
where st.StuName=sc.name
group by name,st.StuNo
order by 總分 desc

用RANK() 會出現相同名次的情況

如:

成績 名次
92 1
92 1
90 3

而使用ROW_NUMBER() 則不會出現這種情況

代碼如下:

select st.StuNo, name as 姓名 ,
max(case course when '語文' then score else 0 end) 語文,
max(case course when '數學' then score else 0 end) 數學,
max(case course when '物理' then score else 0 end) 物理,
sum(score) as 總分,
ROW_NUMBER() OVER(ORDER BY sum(score)desc)  as 名次
from Student as st,Score as sc
where st.StuName=sc.name
group by name,st.StuNo
order by 總分 desc

如:

成績 名次
92 1
92 2
90 3
   
   
   
   

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章