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() 会出现相同名次的情况
如:
而使用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
如:
本文出自 “糖炒栗子” 博客,请务必保留此出处http://tangchaolizi.blog.51cto.com/3126463/1028638
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 |
代码如下:
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 |
相关文章推荐
- Sql 2000 行列转换
- 行列转换等经典SQL语句
- [数据库] SQL查询语句表行列转换及一行数据转换成两列
- sql中时间日期操作(时间日期函数,时间日期格式,时间日期转换参数,时间日期比较,时间日期计算)
- sql表格转置(sql表行列转换)
- SQL 行列转换--经典案例
- SQL行列转换实战
- 第97课: 使用Spark Streaming+Spark SQL+mysql 实现在线动态计算出特定时间窗口下的不同种类商品中的热门商品排名(详细内幕版本)
- 浅析SQL语句行列转换的两种方法 case...when与pivot函数的应用
- SQL中行列转换 Pivot UnPivot
- sql 时间行列转换求总和
- SQL 行列转换数据转换为字符串
- 数据透视表sql:用SQL行列转换实现数据透视的一些思考
- sql行列转换问题 .
- SQL行列转换
- SQL 行列转换,sql2000和2005--多行转一行
- 行列转换等经典SQL语句
- SQL行列转换的另一种方法
- sql为了实现转换的行列
- 动态SQL的使用例子, 行列转换.