Conditional RowNumber
Asked Answered
D

2

10

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
Demerol answered 23/7, 2015 at 14:37 Comment(1)
You should tag your question with the database you are using.Wilmer
W
21

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
Wilmer answered 23/7, 2015 at 14:47 Comment(3)
RoomNm in language above the code should be RoomnumEchevarria
can you help me understand what the 'case when' does within the 'partition by' clause?Echevarria
It does the same thing as it does elsewhere. The purpose is to separate the NULL values.Wilmer
G
0
--I think you can work around this way 
--I have little different scenario but hope logic help

declare @ts table
    (WK_DAYS int
    ,DAY_NAME VARCHAR(12)
    ,WORKTYPE   varchar(50)
    ,WK_HOURS   int
    ,workday int)

insert into @ts (WK_DAYS,DAY_NAME,WORKTYPE,WK_HOURS) values (1,'MON','SICK',8)
insert into @ts (WK_DAYS,DAY_NAME,WORKTYPE,WK_HOURS) values (2,'TUE','LABOR',8)
insert into @ts (WK_DAYS,DAY_NAME,WORKTYPE,WK_HOURS) values (3,'WED','LABOR',8)
insert into @ts (WK_DAYS,DAY_NAME,WORKTYPE,WK_HOURS) values (4,'THU','VACATION',8)
insert into @ts (WK_DAYS,DAY_NAME,WORKTYPE,WK_HOURS) values (5,'FRI','LABOR',8)
insert into @ts (WK_DAYS,DAY_NAME,WORKTYPE,WK_HOURS) values (6,'SAT','LABOR',8)
insert into @ts (WK_DAYS,DAY_NAME,WORKTYPE,WK_HOURS) values (7,'SUN','LABOR',8)

SELECT * FROM @TS

SELECT
    X.*
    ,Y.WORKING_DAY
FROM
(SELECT * FROM @ts)X
    LEFT JOIN
(SELECT *,ROW_NUMBER()OVER (ORDER BY WK_DAYS) AS WORKING_DAY FROM @ts WHERE WORKTYPE NOT IN ('SICK','VACATION','SATURDAY','SUNDAY'))Y
ON X.WK_DAYS = Y.WK_DAYS
Gunyah answered 19/5, 2017 at 16:56 Comment(1)
Can you explain a little more about how you are solving the problem and what the original poster is doing wrong?Whitcomb

© 2022 - 2024 — McMap. All rights reserved.