学生表(student)id(主键) name(姓名) age(年龄) score(学分)1 张安 20 89
2 王五 21 63
3 马克 19 90
4 王虎 20 78
5 陈潭秋 19 87
6 李四 22 89
1、SQL语句 查询学分前3名学生信息(名次可并排),查询结果 应该是 90、89、89、872、同上前3名,根据学分去重复,查询结果 应该是 90、89、87学生的信息
环境是SQL SERVER 2000
2 王五 21 63
3 马克 19 90
4 王虎 20 78
5 陈潭秋 19 87
6 李四 22 89
1、SQL语句 查询学分前3名学生信息(名次可并排),查询结果 应该是 90、89、89、872、同上前3名,根据学分去重复,查询结果 应该是 90、89、87学生的信息
环境是SQL SERVER 2000
select * from student where score in (secect top 3 score from student group by score order by score dssc) order by score desc
drop table tb
Go
Create table tb([id] int,[name] nvarchar(3),[age] int,[score] int)
Insert tb
select 1,N'张安',20,89 union all
select 2,N'王五',21,63 union all
select 3,N'马克',19,90 union all
select 4,N'王虎',20,78 union all
select 5,N'陈潭秋',19,87 union all
select 6,N'李四',22,89
Go
;with tt as
(
select cnt=dense_rank()over(order by [score] desc),*
from tb)
select *
from tt
where cnt<=3
/*
cnt id name age score
-------------------- ----------- ---- ----------- -----------
1 3 马克 19 90
2 1 张安 20 89
2 6 李四 22 89
3 5 陈潭秋 19 87(4 row(s) affected)
*/
select *,sc=(select count(1) + 1 from student b where b.score>a.score)
from student a
where sc <=3
order by scsql 2005下
;with stud as
(
select cnt=dense_rank()over(order by [score] desc),*
from student)
select *
from stud
where cnt<=3
insert into student values(1 ,'张安' ,20 ,89)
insert into student values(2 ,'王五' ,21 ,63)
insert into student values(3 ,'马克' ,19 ,90)
insert into student values(4 ,'王虎' ,20 ,78)
insert into student values(5 ,'陈潭秋' ,19 ,87)
insert into student values(6 ,'李四' ,22 ,89)
go
--1、SQL语句 查询学分前3名学生信息(名次可并排),查询结果 应该是 90、89、89、87
select id,name,age,score from
(
select t.* , px = (select count(distinct score) from student where score >= t.score) from student t
) m
where px <= 3
order by px
/*
id name age score
----------- ---------- ----------- -----------
3 马克 19 90
1 张安 20 89
6 李四 22 89
5 陈潭秋 19 87(所影响的行数为 4 行)
*/--2、同上前3名,根据学分去重复,查询结果 应该是 90、89、87学生的信息
--这个和上面的不是一样?
select id,name,age,score from
(
select t.* , px = (select count(distinct score) from student where score >= t.score) from student t
) m
where px <= 3
order by px
/*
id name age score
----------- ---------- ----------- -----------
3 马克 19 90
1 张安 20 89
6 李四 22 89
5 陈潭秋 19 87(所影响的行数为 4 行)
*/--还是需要这样的效果?
select id,name,age,score from
(
select t.* , px = (select count(score) from student where score > t.score) + 1 from student t
) m
where px <= 3
order by px
/*
id name age score
----------- ---------- ----------- -----------
3 马克 19 90
6 李四 22 89
1 张安 20 89(所影响的行数为 3 行)
*/drop table student