代码之家  ›  专栏  ›  技术社区  ›  Edamame

PostgreSQL:基于列值转换列

  •  3
  • Edamame  · 技术社区  · 7 年前

    col_A 在我的表中,基于如下值:

    col_A
    ----------------------------
    Hello_axd_sdc_we_world
    Hello_g_world
    Hello_world
    Goodbye_A
    Goodbye_sdg_Sda
    Goodbye
    Goodbye_asd_asd_Sddg
    

    我想要转换后的列 d_col_A

    col_A                            d_col_A
    -----------------------------------------
    Hello_axd_sdc_we_world           Hello_world 
    Hello_g_world                    Hello_world 
    Hello_world                      Hello_world 
    Goodbye_A                        Goodbye
    Goodbye_sdg_Sda                  Goodbye
    Goodbye                          Goodbye
    Goodbye_asd_asd_Sddg             Goodbye
    

    以下是我的规则:

    If col_A starts with Hello and end with World
       Then d_col_A = Hello_Wolrd
    If col_A starts with Goodbye
       Then d_col_A = Goodbye
    

    这可能吗?谢谢

    1 回复  |  直到 6 年前
        1
  •  1
  •   Twelfth    7 年前

    创建一个名为“lookup”的表或其他类似于ID、first\u param、second\u param、translate\u value的表

    1,hello,world,hello_world
    2,goodbye,null,goodbye
    

    现在一些人加入了乐趣。Postgres有一个left()和right()以及length()函数,我们可以在这里使用。更复杂的规则集也可以包含类似的函数(第三个参数=必须包含这个词?)如果需要。

    Select a.col_A , l.translate_value
    from table_a a
    left join lookup_table l
      on left(a.col_a,length(l.first_param)) = l.first_param
      and (right(a.col_a,length(l.second_param)) = l.second_param or l.second_param is null)
    

    我做了一个左连接,这样在不满足规则时生成null,而不是删除行。我缺少postgres测试环境,但语法应该是正确的。

    select case when left(col_a,5) = hello and right(col_a,5) = 'world' then 'hello world' 
    case when left(col_a,7) = 'goodbye' then goodbye
    else 'no clue what this means'
    from table_a