条件行号

时间:2015-07-23 14:37:08

标签: sql sql-server sql-server-2012 row-number

我试图根据RowNum列的结果放置条件编号。

当RowNum为1时,我希望新列的全新增量为1。

enter image description here

在RoomNum 5栏中的图片应该被2,9替换3m 13乘4等等。在这个查询中我做错了什么?

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

2 个答案:

答案 0 :(得分:6)

您需要根据RoomNm是否NULL进行分区。结果值也会有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

答案 1 :(得分:1)

--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