2017-02-07 59 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 
相關問題