今天在工作中要写这样的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
三种的查询结果都一样,
至于三种的查询速度快慢,自己没研究,有时间在看!