使用DENSE_RANK

时间:2016-10-11 18:38:47

标签: sql sql-server rank dense-rank

Dense_Rank正在考虑所有因素。有没有办法排除空值,所以1之后的下一个排名是2而不是3。

这就是现在的表格:

 A     | DENSE_R 
 --------------
 1     | 1  
 --------------
 2     | null  
 --------------
 3     | 3 
 --------------
 4     |  4    

这就是我想要的表格:

 A     | DENSE_R 
 --------------
 1     | 1  
 --------------
 2     | null  
 --------------
 3     | 2 
 --------------
 4     |  3  

我正在使用以下代码: -

WITH CTE AS
(
 SELECT A 
 FROM A1
)
SELECT A,
CASE 
  WHEN  **Condition**
  THEN DENSE_RANK() OVER (Order by [A] ASC)
END
AS 'DENSE_R'
FROM CTE

2 个答案:

答案 0 :(得分:5)

您可以像这样使用case

select A,
       (case when A is not null
             then dense_rank() over (partition by (case when A is not null then 1 else 0 end)
                                     order by a desc
                                    )
        end) as dr
from A1;

答案 1 :(得分:5)

使用partition by与您已使用的**Condition**相同。

WITH CTE AS
(
 SELECT A 
 FROM A1
)
SELECT A,
CASE 
  WHEN  **Condition**
  THEN DENSE_RANK() OVER (Partition by (case when **Condition** then 1 else 0 end) Order by [A] ASC)
END
AS 'DENSE_R'
FROM CTE