(select top 3 * from 表1 where 班别='高一2' order by 总分 desc) union (select top 3 * from 表1 where 班别='高二' order by 总分 desc) union (select top 3 * from 表1 where 班别='高三' order by 总分 desc)用Union语句连接
只用一句SQL实现不了这个功能。
select 表1.班别,MAX(表1.总分) AS 最高成绩 from 表1 group by 表1.班别
好好学学group by和having子句吧,很有用处的.
select 表1.班别,MAX(表1.总分) AS 最高成绩 from 表1 group by 表1.班别 你就试试这个语句吧,我以前用过的.如果没写错肯定可以的.
--建立测试环境 create table T(学号 varchar(10),班级 varchar(10),总分 int) insert into T(学号,班级,总分) select 'x_001','A',40 union all select 'x_002','B',60 union all select 'x_003','C',90 union all select 'x_004','A',10 union all select 'x_005','A',20 union all select 'x_006','A',30 union all select 'x_007','B',40 union all select 'x_008','B',90 union all select 'x_009','B',100 union all select 'x_010','C',32 union all select 'x_011','C',54 union all select 'x_012','C',73 union all select 'x_013','C',23 --代码 select 班级,学号,总分 from T a where 总分 in (select top 3 总分 from T where 班级=a.班级 order by 总分 desc) group by 班级,学号,总分 --删除测试环境 drop table T
--返回结果班级 学号 总分 ---------- ---------- ----------- A x_001 40 A x_005 20 A x_006 30 B x_002 60 B x_008 90 B x_009 100 C x_003 90 C x_011 54 C x_012 73
晕,我看成了成绩最高一个,想简单了.whbo答的就很好.
select top 3 班级,学号,总分 from 表1 group by 班级,学号,总分 order by 总分 desc
whbo(王红波(年轻人,要有所作为)) 的是正解: select 班级,学号,总分 from T a where 总分 in (select top 3 总分 from T where 班级=a.班级 order by 总分 desc) group by 班级,学号,总分
whbo的方法好! 学了一招。
--返回结果只是第一个班别的班级 学号 总分 ---------- ---------- ----------- A x_001 40 A x_005 20 A x_006 30
GROUP BY, 只是把结果分组
如果确为总分前三名,则top 3 的返回,会有问题。也就是总分相同的情况
select * from table a where (select count(*) from table b where a.成绩<b.成绩)<3
select * from table a where (select count(*) from table b where a.成绩<b.成绩 and a.班级=b.班级)<3
from 表1
group by 表1.班别
from 表1
group by 表1.班别
你就试试这个语句吧,我以前用过的.如果没写错肯定可以的.
create table T(学号 varchar(10),班级 varchar(10),总分 int)
insert into T(学号,班级,总分)
select 'x_001','A',40 union all
select 'x_002','B',60 union all
select 'x_003','C',90 union all
select 'x_004','A',10 union all
select 'x_005','A',20 union all
select 'x_006','A',30 union all
select 'x_007','B',40 union all
select 'x_008','B',90 union all
select 'x_009','B',100 union all
select 'x_010','C',32 union all
select 'x_011','C',54 union all
select 'x_012','C',73 union all
select 'x_013','C',23 --代码
select 班级,学号,总分 from T a where 总分 in (select top 3 总分 from T where 班级=a.班级 order by 总分 desc)
group by 班级,学号,总分 --删除测试环境
drop table T
---------- ---------- -----------
A x_001 40
A x_005 20
A x_006 30
B x_002 60
B x_008 90
B x_009 100
C x_003 90
C x_011 54
C x_012 73
select 班级,学号,总分 from T a where 总分 in (select top 3 总分 from T where 班级=a.班级 order by 总分 desc)
group by 班级,学号,总分
学了一招。
---------- ---------- -----------
A x_001 40
A x_005 20
A x_006 30
的返回,会有问题。也就是总分相同的情况
where (select count(*) from table b where a.成绩<b.成绩)<3
where (select count(*) from table b where a.成绩<b.成绩 and a.班级=b.班级)<3