Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional RowNumber

I am trying to put conditional numbering depending on a result from RowNum column.

When the RowNum is 1 I would like to have new column with brand new increment by 1.

enter image description here

In the picture in column RoomNum 5 should be replaced by 2, 9 by 3m 13 by 4, etc. What am I doing wrong in this query?

SELECT  CASE 
        WHEN rownum < 2
    THEN
    Row_number() OVER (
        PARTITION BY Scheme ORDER BY Scheme ASC
        )  
    ELSE NULL
END AS RoomNum,

CASE 
    WHEN rownum > 1
        THEN NULL
    ELSE scheme
    END AS Scheme
,RowNum
like image 435
Marek Avatar asked Jul 23 '15 14:07

Marek


People also ask

What is ROW_NUMBER () function then what is the use of over () clause?

ROW_NUMBER function is a SQL ranking function that assigns a sequential rank number to each new record in a partition. When the SQL Server ROW NUMBER function detects two identical values in the same partition, it assigns different rank numbers to both.

What is difference between rank () ROW_NUMBER () and Dense_rank () in SQL?

row_number numbers the rows 1, 2, 3, etc by the columns in the ORDER BY clause, and if there are ties, it is arbitrary which rows that gets the same number. rank and dense_rank are similar to row_number , but when there are ties, they will give the same value to the tied values.

What is ROW_NUMBER () over partition by in SQL?

The Row_Number function is used to provide consecutive numbering of the rows in the result by the order selected in the OVER clause for each partition specified in the OVER clause. It will assign the value 1 for the first row and increase the number of the subsequent rows.

What is the difference between ROW_NUMBER and Rownum?

ROWNUM is the sequential number, allocated to each returned row during query execution. ROW_NUMBER assigns a number to each row according to its ordering within a group of rows. ROW_NUMBER is a function that returns numeric value.


1 Answers

You need to partition by whether or not RoomNm is NULL. The resulting value would also have a CASE:

select (case when roomnum is not null
             then row_number() over (partition by scheme, (case when roomnum is not null then 1 else 0 end)
                                     order by roomnum
                                    )
        end) as RoomNum
like image 132
Gordon Linoff Avatar answered Sep 28 '22 07:09

Gordon Linoff