当前一行号为NULL时跳过行号

时间:2017-02-15 09:28:56

标签: sql-server row-number

我想在前一行号为NULL时跳过行号 我的查询如下

select O.Id as orderItemID,Custom,
    CustomName=(CASE WHEN Custom=1 THEN 'Left' When Custom=2 Then 'Right' Else '' END),
    RowNumber = (CASE WHEN Custom = '2' THEN NULL ELSE Row_Number() OVER(ORDER BY O.ID) END )
    From  dbo.OrderItem O 
    left join SubCategory I On O.ItemId=I.ItemId 
    left join ItemType IT On O.Size=IT.TypeId
    where O.OrderId=@OrderId
order by O.Id 

我的输出是

enter image description here

我想要的输出

enter image description here

任何人都可以帮帮我

1 个答案:

答案 0 :(得分:3)

您需要将ROW_NUMBER()PARTITION BY CASE WHEN Custom = 2 THEN 1 ELSE 0 END一起使用,为Custom = 2所在的行创建单独的(隐藏)计数器:

SELECT   O.Id as orderItemID
        ,Custom
        ,CustomName =(CASE WHEN Custom=1 THEN 'Left' When Custom=2 Then 'Right' Else '' END)
        ,RowNumber = CASE WHEN Custom = 2 THEN NULL ELSE ROW_NUMBER() OVER (PARTITION BY CASE WHEN Custom = 2 THEN 1 ELSE 0 END ORDER BY O.ID) END
FROM  dbo.OrderItem O 
    LEFT JOIN SubCategory I On O.ItemId=I.ItemId 
    LEFT JOIN ItemType IT On O.Size=IT.TypeId
WHERE O.OrderId=@OrderId
ORDER BY O.Id