SQL SERVER根据表的相同某几列数据查询某列最大的前几行

今天在工作中要写这样的SQL,半天没写出来,查了下资料才写出来,,记录下来以免以后又忘了。

比如,现在要查询每个学生成绩最大的前两个科目;

我们首先建表插入数据,

create table #a ( Name varchar(10),score int,course varchar(10))
insert into #a values ('张三',85,'语文'),
					  ('李四',55,'数学'),
					  ('张三',75,'物理'),
					  ('李四',95,'语文'),
					  ('李四',88,'政治'),
					  ('张三',99,'生物')

表数据如下:
在这里插入图片描述
目前我找到有三种方式查询;
第一种,使用in进行操作;

select a.* from #a a 
where score in (select top 2 score from #a where Name=a.Name order by score desc) 
order by a.Name,a.score desc

第二种,使用>操作;

select a.* from #a a 
where 2 > (select count(*) from #a where Name = a.Name and score > a.score ) 
order by a.Name,a.score desc

第三种,使用exists查询;

SELECT a.* from #a a 
where exists (select count(*) from #a where Name = a.Name and score > a.score having Count(*) < 2) 
order by a.Name,a.score desc

三种的查询结果都一样,
在这里插入图片描述
至于三种的查询速度快慢,自己没研究,有时间在看!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值