--使用ROW_NUMBER()或rant()[如同分数同名次] 函数
select t.Subject,t.Amount,t.Name,t.Age ,t.*
from (
select
ROW_NUMBER() over(partition by i.Subject order by i.Amount desc) inum,
u.Name,u.Age,i.Subject,i.Amount
from Income i
join [User] u on i.UserId = u.ID
) t
where t.inum<3
order by t.Subject, t.Amount desc;
--条件排除
select distinct t1.Subject,t1.Amount,u1.Name,u1.Age
from Income as t1
join [User] u1 on t1.UserId = u1.ID
where t1.Id in
(
select top 2 t2.Id from Income as t2
join [User] u2 on t2.UserId = u2.ID
where t1.Subject=t2.Subject
order by t2.Amount desc
)
order by Subject, Amount desc;
-- 此方法如有重复的值不适合取前几位,可用于去比较值
select a.*
from Income a where (select count(1) from Income where Subject=a.Subject and Amount>a.Amount)<=1