为什么交叉应用给出所有行而不是前 N

why the cross apply is giving all the rows and not top N

我有一个table

name    score
samar   12
pradeep 30
garry   90

我想从上面的table中获得前2名的分数。这可以通过 row_number() 函数来完成。但它也应该与交叉应用一起使用。但是我下面提到的代码给出了所有行而不是前 2 个分数。

select abc.score
from #b as a
cross apply (
    select top 2 score
    from #b as 
    where b.name = a.name
    order by b.score desc
) as abc

你能告诉我上面的代码有什么问题吗?

请检查以下查询是否适用于您的情况。

create table #b
(name varchar(30), score int);


insert into #b (name, score)
values ('mohit',12),
('pradeep',30),
('garry',42)


SELECT name,
       score,
       ROW_NUMBER() OVER(ORDER BY Score) RN
INTO #c
FROM #b

SELECT name,
       score,
       CONVERT(NUMERIC,score)/
       (SELECT SUM(score)
        FROM #c
        WHERE RN <= 2) Percentage
FROM #c
WHERE RN <= 2