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.
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
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With