日期:2014-05-18  浏览次数:20438 次

求一SQL语句,只返回结果集中的前N行
表:

id       class       name
1         0701         张三
2         0702         王明
3         0703         刘若英
4         0702         张静初
5         0702         李太兰
6         0703         孔孝真

如上表,我要结果返回每一个班的前两名,怎么办?top好像只能在总的结果集取前N个记录,我的要分类。



------解决方案--------------------
form--> from,笔误
select * from tb
where id in (select top 2 id from tb as t where class=tb.class)

------解决方案--------------------
select * from tb a
where id in (select top 2 id from tb where class=a.class order by id) order by class,id
------解决方案--------------------
楼主 那么怎么判断班级的前二名呢 你又没有分数

------解决方案--------------------
SELECT * FROM TABLE AS PQS
WHERE ID IN (SELECT TOP 2 ID FROM TABLE WHERE CLASSID=PQS.CLASSID )