【SQL】分组取每组前几条记录

按name分组取最大的两个val:

[比当前记录val大的条数]小于2条;即当前记录为为分组中的前两条

1 select a.* from tb a where 2 > (select count(*) from tb where name = a.name and val > a.val ) order by a.name,a.val;
2 select a.* from tb a where val in (select top 2 val from tb where name=a.name order by val desc) order by a.name,a.val;
3 select a.* from tb a where exists (select count(*) from tb where name = a.name and val > a.val having Count(*) < 2) order by a.name;

 

posted @ 2018-08-20 15:30  是谁扭曲了时空  阅读(1282)  评论(0编辑  收藏  举报