【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;