【问题标题】:Specify row number start point指定行号起点
【发布时间】:2021-05-06 09:01:53
【问题描述】:

我在下面有一些示例数据,我想使用 row_number 但在 col3 的值为 0 时启动它 我尝试了以下方法,但它不起作用

row_number() over (partition by col1,col2, case when col3 = 0 then 1 end order by col4 desc) as row2
Col1 col2 col3 col4 row_number (output wanted)
abc def 7 500
abc def 0 300 1
abc def 1 200
abc def 0 2 2
abc def 4 30

【问题讨论】:

    标签: sql postgresql


    【解决方案1】:

    其他人为 NULL

    case when col3 = 0  
       then row_number() over (partition by col1,col2, col3 order by col4 desc) end as row2
    

    【讨论】:

      【解决方案2】:

      行号只是行的连续计数。所以你应该能够做到这一点:

      select
        col1, col2, col3, col4,
        count(case when col3 = 0 then 1 end)
          over (partition by col1, col2 order by col4 desc, ctid) as row2
      from ...
      order by col1, col2, col4 desc, ctid;
      

      我添加了 Postgre 的内部 CTID 以便为 col4 值重复的情况获得确定的顺序。如果这样的重复是不可能的,您可以从ORDER BY 子句中删除CTID

      【讨论】:

      • 是的,如果 col4 具有相同的值,我需要一些可以工作的东西。
      • 我刚刚发现了 Postgre 的 CTID 并更新了我的答案。
      • 一个问题是我正在使用 redshift 并且它没有 CTID
      【解决方案3】:

      谢谢大家,但我刚刚想通了。

      我做到了

      case when col3 =0 then row_number() over (partition by col1,col2,col3=0 order by col4 desc) else null end as Row
      

      所以这是对两组 0 和非 0 的运行计数,我只是用案例隐藏非 0 的。

      【讨论】:

      • 这类似于 Serg 在他们的回答中建议的内容。但是,您需要一个确定的顺序,以便行号与您显示结果的顺序相匹配。这也意味着在这里,您应该将 CTID 添加到 ORDER BY 子句中,正如我在回答中所显示的那样。
      • 嗨,我使用的是 Redshift,所以它没有 CTID
      • 那为什么你的请求被标记为postgresql?如果没有任何内置功能可帮助您获得确定性订单,请为此目的在表中添加技术 ID。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多