仅当subselect不为null时才插入值

时间:2016-05-02 20:08:01

标签: sql postgresql

我正在尝试编写将使用现有表中的数据创建新表的sql。 除了其他列之外,新表将包含两列,如下所示:

reserved  boolean
reserved_for character varying(10)

原始表格中,我的数据如下所示:

     id      | identification |             department             |                description                |     lastchange      | available |  type  
------------+----------------+------------------------------------+-------------------------------------------+---------------------+-----------+--------
 9145090050 |                |                                    | Reserved for llb                          | 2011-05-20 11:46:21 | f         | 
 9145090096 |                |                                    | Reserved for ppa                          | 2013-01-26 12:31:56 | f         | 
 9145090046 |                |                                    |                                         | 2011-05-06 10:34:21 | f         | 

如果原始表格中包含文字"保留..."那么,我希望新表中的保留字段设置为" true"和reserved_for包含"保留为"后面的3或4个字符。原始表格中的文字 因此,使用上表作为示例,我希望我的新表看起来像这样;

     id     | reserved |  reserved_for  |  lastchange         |  
------------+----------+----------------+---------------------+
 9145090050 | true     | llb            | 2011-05-20 11:46:21 |  
 9145090096 | true     | ppa            | 2013-01-26 12:31:56 | 
 9145090046 | false    |                | 2011-05-06 10:34:21 |

查询我必须在"保留为"之后提取4个字符。看起来像这样:

   select 
      substring(description from 13 for 4) 
   from
      definition 
   where 
      description like 'Reserved for%';

它起作用,它提取我需要的字符。如何在create table命令中编写条件语句?

2 个答案:

答案 0 :(得分:1)

我认为这只是原始表上的一些字符串操作:

select id,
       (description like 'Reserved for%') as Reserved,
       (case when description like 'Reserved for%'
             then substring(description from 14) 
        end) as Reserved_For,
       last_change
from original;

答案 1 :(得分:0)

也许这会有所帮助..

insert into yourtable(id,reserved,reserved_for,lastchange)
select t1.id, 
       case when t1.description like 'Reserved for%' then true else false end as reserved,
       case when when t1.description like 'Reserved for%' then substr('reserved for llb',strpos('reserved for llb','for') + 4) else null end as reserved_for,
       lastchange
from table t1