Search code examples
sqldashdb

SQL ROW_NUMBER()OVER(PARTITION BY with conditions


I understand the basics of Row_Number but how do you use it with some conditions. So, I need the number of an instance of a value in col1 BUT only where col2 is not null and col2 is null.

So, I have this:

col1    col2    col3
Orange  x       x
Orange  x   
Orange  x   
Banana          x
Banana      
Orange          x
Apple   x   
Aplle   x   
Banana  x   
Orange  x       x

and I need this:

col1    col2    col3    newcol
Orange  x       x   
Orange  x               3
Orange  x               3
Banana          x   
Banana          
Orange          x   
Apple   x               2
Aplle   x               2
Banana  x               1
Orange  x       x       3

I am running under dashDB.


Solution

  • As I understand that you need quantity of col1 where col2 is null and quantity of col1 where col2 is not null If so, try this, please

    select col1, new_col, count(1)
    from
    (
    select col1, "not_null" as new_col
    from table
    where
      col2 is not null
    union
    select col1, "is_null" as new_col
    from table
    where
      col2 is null
    )
    group by col1, new_col