Exclude null values using DENSE_RANK

你离开我真会死。 提交于 2019-12-22 07:05:54

问题


Dense_Rank is taking everything into account. Is there a way to exclude the null values so the next rank after 1 would be 2 and not 3.

This is what the table looks like now:

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

This is what I want the table to look like:

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

I'm using the following code to do so:-

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

回答1:


Use partition by the same **Condition** as you used already.

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



回答2:


You can use case like this:

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;


来源:https://stackoverflow.com/questions/39984393/exclude-null-values-using-dense-rank

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!