如果列符合条件,则转换列的条目

时间:2015-08-28 05:52:18

标签: sql postgresql

我的表中有一个列(部门)有4个不同的值:(department1,department2,department3或department4)。我想做的是根据标准将文本转换为其他内容,以便更容易理解。

非常简单地说:

IF departments = "department1" then re-write department1 as Finance
IF departments = "department2" then re-write department2 as HR
IF departments = "department3" then re-write department2 as Service
etc...

然后,部门专栏将如下所示:

departments
-----------
department1
department1
department3
department1
etc..

departments
-----------
Finance
Finance
Service
Finance
etc..

我一直在寻找很长一段时间,找不到任何办法,我甚至不确定它是否可能。如果之前有人问过,请道歉。

2 个答案:

答案 0 :(得分:1)

如果要选择该格式的数据,请执行此操作

select 
case when departments = 'department1' then 'Finance'
     when departments = 'department2' then 'HR'
     when departments = 'department3' then 'Service'
     when departments = 'department4' then '4th dept'
end
from table_name

如果你想更新表

UPDATE table_name
SET     departments =  
    case when departments = 'department1' then 'Finance'
         when departments = 'department2' then 'HR'
         when departments = 'department3' then 'Service'
         when departments = 'department4' then '4th dept'
    end

答案 1 :(得分:0)

如果您想要就地更新数据,请使用简单的

update mytable set departments = 'Finance' where departments = 'department1'

如果您想保留数据,只更改select语句返回的内容,请使用case

select
  case departments
    when 'department1' then 'Finance'