Reputation: 3575
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
Upvotes: 10
Views: 28166
Reputation: 9
--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
Upvotes: 0
Reputation: 1269503
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
Upvotes: 21