将if语句与row_number一起使用,然后使用

发布于 2025-01-23 03:44:10 字数 599 浏览 0 评论 0原文

我已经尝试创建下面的代码,但对我不起作用。

我要做的是使用row_number,但是请检查列MP ='yes',然后+1 to 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

I have tried creating the code below but it didn't work for me.

what I'm trying to do is use Row_number however check if the column MP =' Yes' then +1 to the Row_number value if it does otherwise just give me the 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

enter image description here

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

分分钟 2025-01-30 03:44:10

如果我正确理解,则可以尝试使用sum window>在时使用时,如果mp是YES是添加一个。

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

If I understand correctly, you can try to use SUM window function with CASE WHEN, if MP is yes add one more.

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
浅暮の光 2025-01-30 03:44:10

i think 您实际想要的是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];

I think what you actually want is a ROW_NUMBER and a conditional running 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];
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文