sql server 查询记录平均值及并排序 的语句
程序员文章站
2023-12-27 10:02:57
...
sql server 查询记录平均值及并排序 的语句
查询学生的平均成绩并进行排名,sql 2000用子查询完成,分平均成绩重复时保留名次空缺和不保留名次空缺两种。
select t1.* , px = (select count(1) from
(
select m.S# [学生编号] ,
m.Sname [学生姓名] ,
isnull(cast(avg(score) as decimal(18,2)),0) [平均成绩]
from Student m left join SC n on m.S# = n.S#
group by m.S# , m.Sname
) t2 where 平均成绩 > t1.平均成绩) + 1 from
(
select m.S# [学生编号] ,
m.Sname [学生姓名] ,
isnull(cast(avg(score) as decimal(18,2)),0) [平均成绩]
from Student m left join SC n on m.S# = n.S#
group by m.S# , m.Sname
) t1
order by px
查询学生的平均成绩并进行排名,sql 2000用子查询完成,分平均成绩重复时保留名次空缺和不保留名次空缺两种。
select t1.* , px = (select count(1) from
(
select m.S# [学生编号] ,
m.Sname [学生姓名] ,
isnull(cast(avg(score) as decimal(18,2)),0) [平均成绩]
from Student m left join SC n on m.S# = n.S#
group by m.S# , m.Sname
) t2 where 平均成绩 > t1.平均成绩) + 1 from
(
select m.S# [学生编号] ,
m.Sname [学生姓名] ,
isnull(cast(avg(score) as decimal(18,2)),0) [平均成绩]
from Student m left join SC n on m.S# = n.S#
group by m.S# , m.Sname
) t1
order by px
select t1.* , px = (select count(distinct 平均成绩) from
(
select m.S# [学生编号] ,
m.Sname [学生姓名] ,
isnull(cast(avg(score) as decimal(18,2)),0) [平均成绩]
from Student m left join SC n on m.S# = n.S#
group by m.S# , m.Sname
) t2 where 平均成绩 >= t1.平均成绩) from
(
select m.S# [学生编号] ,
m.Sname [学生姓名] ,
isnull(cast(avg(score) as decimal(18,2)),0) [平均成绩]
from Student m left join SC n on m.S# = n.S#
group by m.S# , m.Sname
) t1
order by px
/*
数据表结构
--1.学生表
Student(S#,Sname,Sage,Ssex) --S# 学生编号,Sname 学生姓名,Sage 出生年月,Ssex 学生性别
--2.课程表
Course(C#,Cname,T#) --C# --课程编号,Cname 课程名称,T# 教师编号
--3.教师表
Teacher(T#,Tname) --T# 教师编号,Tname 教师姓名
--4.成绩表
SC(S#,C#,score) --S# 学生编号,C# 课程编号,score 分数