【问题标题】:compare special string in sql比较sql中的特殊字符串
【发布时间】:2020-04-29 14:27:19
【问题描述】:

我是使用 sql 的新手。 我试图比较我的表 client 中列 type 的内容。 如果此列以 XXX 开头,那么我想创建具有特定值 cat1 的新列。 如果此列以 XXY 开头然后 CAT2,如果此列以 XYY 开头然后 CAT3,

select  name, if SUBSTRING(type, 1, 3)=='XXX' then 'CAT1' as x2
from client. 

【问题讨论】:

    标签: sql string postgresql compare substring


    【解决方案1】:

    你想要case。我会推荐like

    select  name, (case when type like 'XXX%' then 'CAT1' end) as x2
    from client;
    

    【讨论】:

      【解决方案2】:

      您可以使用CASE。例如:

      select
        name,
        case when type like 'XXX%' then 'cat1'
             when type like 'XXY%' then 'cat2'
             when type like 'XYY%' then 'cat3'
        end as category
      from client
      

      【讨论】:

      • 好的,谢谢。检测字符串的结尾。我想检测类型以 XYY 开头并以 C1 结尾的行我做了 当类型像 'XYY%' 和类型像 '%C3' 然后 'cat3'
      • 不,不幸的是,我有 XYYBNPC1 及其 NULL 的行:/
      • @salsa 请接受此答案并针对新要求提出另一个问题。
      猜你喜欢
      • 2015-07-15
      • 2015-11-06
      • 1970-01-01
      • 2019-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多