Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exclude null values using DENSE_RANK

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
like image 279
ThatRiddimGuy Avatar asked Oct 11 '16 18:10

ThatRiddimGuy


People also ask

How do you exclude null values?

Hiding null values To filter null dimensions or discrete measures, drag the pill to the Filter shelf and deselect Null. The null value will appear in the list with discrete values, where you can then remove it. When a measure contains null values, they are usually plotted in a view as zero.

What is the difference between the rank () and the Dense_rank () functions?

rank and dense_rank are similar to row_number , but when there are ties, they will give the same value to the tied values. rank will keep the ranking, so the numbering may go 1, 2, 2, 4 etc, whereas dense_rank will never give any gaps.

Can I use dense rank in where clause?

For this reason, you cannot use any of these functions in WHERE : ROW_NUMBER() , RANK() , DENSE_RANK() , LEAD() , LAG() , or NTILE() .


2 Answers

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
like image 143
GriGrim Avatar answered Nov 09 '22 08:11

GriGrim


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;
like image 37
Gordon Linoff Avatar answered Nov 09 '22 07:11

Gordon Linoff