使用密集秩函数的第二个最大值

时间:2015-06-05 08:37:39

标签: sql sql-server-2005

我的表格如下:

name     marks
raja     88
ravi     88
karthik  99
praveen  99
vijay    70

在该表中,我假设表的等级为:

name      marks        rank 
karthirk    99           1
praveen     99           2
raja        88           3
ravi        88           4
vijay       77           5

我通过使用dense rank()函数

来实现
select  name,marks,dense_rank() over(  order by name ) as ranks
from std_D_D order by marks desc

但我需要的是从上面的表中我需要获得第二低的排名。 我的意思是我想要的输出是:

ravi 88   4

我试图获得排名第二的排名,但我无法获得所有排名。我试过这个问题:

select max(a.ranks) as b from (
select  name,marks,dense_rank() over(  order by name ) as ranks
from std_D_D ) as a where a.ranks not in
(

select max(a.ranks) as b from (
select  name,marks,dense_rank() over(  order by name ) as ranks
from std_D_D ) as a )

3 个答案:

答案 0 :(得分:2)

您可以撤消排名顺序并选择第二个:

SELECT name, marks
FROM   (SELECT name, makrs, DENSE_RANK() OVER (ORDER BY name DESC) AS ranks
        FROM   std_D_D) t
WHERE  ranks = 2

答案 1 :(得分:1)

Aswer对我的上述问题:

SELECT * FROM

(SELECT NAME,MARKS,dense_RANK() OVER(ORDER BY RANK DESC,name) AS TEMP_ORDER FROM

(SELECT *,DENSE_RANK() OVER(ORDER BY MARKS DESC,NAME) AS RANK FROM std_D_D) A
) B WHERE TEMP_ORDER=2;

答案 2 :(得分:0)

首先我要说的是,如果您使用DENSE_RANK(),您将获得具有相同分数的人的相同排名,这与您的假设排名不同。

修改

根据OP的评论,添加了额外的ORDER BY name DESC

示例数据

DECLARE @std_D_D table
(
name VARCHAR(10),
marks int
)

insert into @std_D_D values
('raja',    88),
('ravi',    88),
('karthik',  99),
('praveen',  99),
('vijay',    70);

<强>查询

;WITH CTE
AS
(
SELECT name,marks,dense_rank() over(ORDER BY marks ASC,name DESC) as ranks
from @std_D_D
)
SELECT name,marks,ranks
FROM CTE
WHERE ranks = 2

此查询的输出将为您提供

ravi    88  2