有条件的sql查询来获取子字符串

时间:2015-07-23 07:09:17

标签: sql oracle

我有一张表"anx_m1“。IT有以下3个字段

OCCURTIME,OBJECTNAME,ID

值如下所示

22-JUL-15,Installmx_CHX sd:21 postcheck neutral,PNT_22715_13

22-JUL-15,Installmx_F sd:23次检查受影响,PNT_22715_2

22-JUL-15,Installmx_TPONS sd:993 precheck invalid,PNT_22715_131

现在我需要将这些值移动到具有以下逻辑的不同表“amxm_stage”中。

select OCCURTIME,ID,substr(OBJECTNAME,1,13) AS ONAME from anx_m1 where OBJECTNAME like 'Installmx_CHX sd:21%';

select OCCURTIME,ID,substr(OBJECTNAME,1,11) AS ONAME from anx_m1 where OBJECTNAME like 'Installmx_F sd:23%';

select OCCURTIME,ID,substr(OBJECTNAME,1,15) AS ONAME from anx_m1 where OBJECTNAME like 'Installmx_TPONS sd:993%';

我尝试了以上内容。但是,如何才能使用单个sql语句来完成此任务?

2 个答案:

答案 0 :(得分:0)

尝试CASE表达式

SELECT * FROM
(
    select OCCURTIME,ID,
    case 
    when OBJECTNAME like 'Installmx_CHX sd:21%' then substr(OBJECTNAME,1,13) 
    when OBJECTNAME like 'Installmx_F sd:23%' then substr(OBJECTNAME,1,11) 
    when OBJECTNAME like 'Installmx_TPONS sd:993%' then substr(OBJECTNAME,1,15)
    end as ONAME
    from anx_m1 
) T where ONAME is not null

答案 1 :(得分:0)

您可以union all您的查询,但这是更简单的解决方案:

select OCCURTIME, ID, substr(OBJECTNAME,1,instr(objectname, ' ')-1) AS ONAME 
  from anx_m1 
  where OBJECTNAME like 'Installmx_CHX sd:21%'
     or OBJECTNAME like 'Installmx_F sd:23%'
     or OBJECTNAME like 'Installmx_TPONS sd:993%';

SQLFiddle demo