2017-02-07 36 views
1

我想从PostgreSQL中查询创建两个新的栏目,一个,另一个depnding对新列,即根据现有的数据创建依赖PostgreSQL的2分新的条件列

existing_col new_col new_col2 
a    1   2 
b    0   0 

我曾尝试:

select existing_col, 
case when existing_col like 'a' then 1 else 0 end as new_col 
case when new_col like 1 then 2 else 0 end as new_col2 
from table 

但是,这是给我的错误,new_col不存在,我怎么能做到这一点?

+0

你缺少'end'案例 –

+0

有纠正错误仍然无效。 – user124123

+0

您不能在引入别名的同一级别引用'new_col' –

回答

1

更新:

(我修改您的QRY一点没有避免这样运营商的整数)

t=# create table "table" (existing_col text); 
CREATE TABLE 
Time: 50.189 ms 
t=# insert into "table" values('a'),('b'); 
INSERT 0 2 
Time: 0.911 ms 
t=# select *,case when new_col like 1 then 2 else 0 end as new_col2 
t-#  from (
t(#  select existing_col, 
t(#  case when existing_col like 'a' then 1 else 0 end as new_col 
t(#  from "table") al 
t-# ; 
ERROR: operator does not exist: integer ~~ integer 
LINE 1: select *,case when new_col like 1 then 2 else 0 end as new_c... 
           ^
HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts. 
Time: 0.514 ms 
t=#  select *,case when new_col = 1 then 2 else 0 end as new_col2 
t-#  from (
t(#  select existing_col, 
t(#  case when existing_col like 'a' then 1 else 0 end as new_col 
t(#  from "table") al 
t-# ; 
existing_col | new_col | new_col2 
--------------+---------+---------- 
a   |  1 |  2 
b   |  0 |  0 
(2 rows) 

Time: 0.347 ms 

as in docs:

CASE WHEN condition THEN result 
    [WHEN ...] 
    [ELSE result] 
END 
相关问题