您的位置:首页 > 数据库

SQL表行列转换后再计算排名

2012-10-16 20:19 399 查看
行列转换后再加一个总分列,名次列

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() 会出现相同名次的情况

如:

成绩名次
921
921
903
而使用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

如:

成绩名次
921
922
903
本文出自 “糖炒栗子” 博客,请务必保留此出处http://tangchaolizi.blog.51cto.com/3126463/1028638
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: