类似如下数据,想显示平均成绩在班级前60%的学生,请前辈指点!学号 班级 课程 成绩
20090001 计算机 英语 80
20090001 计算机 体育 80
20090001 计算机 语文 80
20090002 会计 英语 80
20090002 会计 体育 80
20090002 会计 语文 80
20090001 计算机 英语 80
20090001 计算机 体育 80
20090001 计算机 语文 80
20090002 会计 英语 80
20090002 会计 体育 80
20090002 会计 语文 80
from tb
group by 学号
select top 60 percent *
from
(select 學號,班級,avg(成績) as '平均成績' from tb group by 學號,班級) a
order by 平均成績
create table [tb]([学号] int,[班级] varchar(6),[课程] varchar(4),[成绩] int)
insert [tb]
select 20090001,'计算机','英语',80 union all
select 20090001,'计算机','体育',80 union all
select 20090001,'计算机','语文',80 union all
select 20090002,'会计','英语',80 union all
select 20090002,'会计','体育',80 union all
select 20090002,'会计','语文',80
--->查询
select *
from tb a,
(select top 60 percent 学号,avg(成绩) as av from tb group by 学号 order by av) b
where a.学号=b.学号/**
学号 班级 课程 成绩 学号 av
----------- ------ ---- ----------- ----------- -----------
20090001 计算机 英语 80 20090001 80
20090001 计算机 体育 80 20090001 80
20090001 计算机 语文 80 20090001 80
20090002 会计 英语 80 20090002 80
20090002 会计 体育 80 20090002 80
20090002 会计 语文 80 20090002 80(所影响的行数为 6 行)
**/
from tb
group by 学号
order by avg(成绩) desc
from tb a,
(select top 60 percent 学号,avg(成绩) as av from tb group by 学号 order by av) b
where a.学号=b.学号/**
学号 班级 课程 成绩
----------- ------ ---- -----------
20090001 计算机 英语 80
20090001 计算机 体育 80
20090001 计算机 语文 80
20090002 会计 英语 80
20090002 会计 体育 80
20090002 会计 语文 80(所影响的行数为 6 行)
**/
select top 60 percent from (select 学号, 班级, sum(成绩)/count(成绩) as 平均成绩 from tb1 group by 学号, 班级) t group by 班级 order by 平均成绩
declare @tb table ([学号] int,[班级] varchar(6),[课程] varchar(4),[成绩] int)
insert @tb
select 20090001,'计算机','英语',80 union all
select 20090001,'计算机','体育',80 union all
select 20090001,'计算机','语文',80 union all
select 20090002,'会计','英语',80 union all
select 20090002,'会计','体育',80 union all
select 20090002,'会计','语文',80--查詢
select top 60 percent *
from (select [班级],[学号],AVG([成绩]) as 平均成績 from @tb group by [班级],[学号]) a
order by [班级],平均成績 desc
-->查学号
select distinct a.学号
from tb a,
(select top 60 percent 学号,avg(成绩) as av from tb group by 学号 order by av) b
where a.学号=b.学号
insert @t
select 20090001,'计算机','英语',60 union all
select 20090001,'计算机','体育',70 union all
select 20090001,'计算机','语文',80 union all
select 20090002,'会计','英语',60 union all
select 20090002,'会计','体育',70 union all
select 20090002,'会计','语文',80
select distinct a.学号
from @t a,
(select top 60 percent 学号,avg(成绩) as av from @t group by 学号 order by av) b
where a.学号=b.学号 学号
-----------
20090001
20090002(2 行受影响)