使用带有 Row_Number 然后 +1 的 If 语句

Using If statement with a Row_Number then +1

我试过创建下面的代码,但它对我不起作用。

我想做的是使用 Row_number 但是请检查列 MP ='Yes' 然后 +1 到 Row_number 值,否则就给我 Row_number.

  SELECT
 [Key]
,[Key2]
,MP
,OriginalOrder = ROW_NUMBER() OVER(Partition by [Key] ORDER BY  [Key],[Key2])
,IIF(MP = 'Yes' , ROW_NUMBER() OVER(Partition by [Key] ORDER BY  [Key],[Key2])+1,ROW_NUMBER() OVER(Partition by [Key] ORDER BY  [Key],[Key2]))what_i_have_tried
FROM
cte_RowNumbertest
ORDER BY
1,2

如果我没理解错的话,你可以尝试用SUM window函数和CASE WHEN,如果MP是的话再加一个

SELECT
     [Key]
    ,[Key2]
    ,MP
    ,ROW_NUMBER() OVER(Partition by [Key] ORDER BY  [Key],[Key2]) OriginalOrder 
    ,SUM(CASE WHEN MP = 'Yes' THEN 2 ELSE 1 END) OVER(Partition by [Key] ORDER BY  [Key],[Key2]) what_i_have_tried
FROM
cte_RowNumbertest
ORDER BY
1,2

认为你真正想要的是一个ROW_NUMBER和一个有条件的运行 COUNT:

 SELECT [Key]
        [Key2],
        MP,
        ROW_NUMBER() OVER (Partition by [Key] ORDER BY [Key],[Key2]) AS OriginalOrder,
        ROW_NUMBER() OVER (Partition by [Key] ORDER BY [Key],[Key2]) +
        COUNT(CASE MP WHEN 'Yes' THEN 1 END) OVER (Partition by [Key] ORDER BY [Key],[Key2]) AS ExpectedOutput
FROM dbo.YourTable
ORDER BY [Key]
         [Key2];