代码之家  ›  专栏  ›  技术社区  ›  Chicken Sandwich No Pickles

SQL CASE语句到字符串中的最后一个字母

  •  0
  • Chicken Sandwich No Pickles  · 技术社区  · 4 年前

    我有一列包含以下值:

    column_1
    1223B
    123C
    028409d
    abce
    ABCf
    

    我想写一个case语句,如果字符串中的最后一个值是小写的,那么它的值为1,否则为0。

    有什么建议吗?

    编辑#1:

    此列中只能找到数字和字母。

    编辑#2:

    字符串的最后一个字符将始终是一个字母。

    3 回复  |  直到 4 年前
        1
  •  1
  •   Alex Poole    4 年前

    根据您希望如何处理不以大写/小写字符结尾的字符串,您可以执行以下操作:

    case when substr(column_1, -1) = lower(substr(column_1, -1)) then 1 else 0 end
    

    或

    case when substr(column_1, -1) != upper(substr(column_1, -1)) then 1 else 0 end
    

    db<>fiddle

    这个 substr(column_1, -1) 给你最后一个角色; from the documentation :

    如果 位置 为负数,则Oracle从的末尾向后计数 烧焦 .

    然后,您可以将其和 lower(...) (或 upper )看看是否匹配。

    您也可以使用正则表达式,但这在这里似乎没有必要。

        2
  •  1
  •   The Impaler    4 年前

    你可以组合 LOWER() 具有 SUBSTR() 以查找最后一个字符是否为小写。例如

    select c, 
      case when lower(substr(c, -1, 1)) = substr(c, -1, 1) 
           then 1 else 0 end as f
    from (
      select '1223B' as c from dual
      union all select '123C' from dual
      union all select '028409d' from dual
      union all select 'abce' from dual
      union all select 'ABCf' from dual
    ) x
    

    后果

     C        F 
     -------- - 
     1223B    0 
     123C     0 
     028409d  1 
     abce     1 
     ABCf     1 
    

    请参阅上的示例 db<>fiddle .

        3
  •  1
  •   Littlefoot    4 年前

    或

    SQL> with test (col) as
      2    (select '1223B'   from dual union all
      3     select '123C'    from dual union all
      4     select '028409d' from dual union all
      5     select 'abce'    from dual union all
      6     select 'ABCf'    from dual union all
      7     select '1234'    from dual
      8    )
      9  select col,
     10         case when regexp_substr(col, '[[:alpha:]]$') = lower(substr(col, -1)) then 1
     11              else 0
     12         end result
     13  from test;
    
    COL         RESULT
    ------- ----------
    1223B            0
    123C             0
    028409d          1
    abce             1
    ABCf             1
    1234             0
    
    6 rows selected.
    
    SQL>