PostgreSQL中的条件语句

时间:2016-10-19 05:14:02

标签: sql postgresql

'select'语句产生一些数据输出序列,如'SL''CL''PL'等,如下图所示 enter image description here

如果数据输出为SL,则应将其转换并显示为“Z”,如果其“CL”为“Q”,如果其“PL”则为“R”

有没有办法实现这个

2 个答案:

答案 0 :(得分:2)

您可以使用CASE WHEN

select case when dbreed1 = 'SL' then 'Z'
            when dbreed1 = 'CL' then 'Q'
            when dbreed1 = 'PL' then 'R'
            else 'other'
       end dbreed1_mapped

您也可以编写自己的函数:

create or replace function map_breed(_input text) returns text as
$$
    select case when _input = 'SL' then 'Z'
                when _input = 'CL' then 'Q'
           end
$$
language sql;

并称之为:

select map_breed('SL');

答案 1 :(得分:0)

create or replace function map_breed(dbreed text) returns text as 
$$ 
   begin 
   select case when dbreed = 'SL' then 'Z' 
               when dbreed = 'CL' then 'Q' end into dbreed; 
   return dbreed;
   end; 
$$ language plpgsql; 

/*and call the function as*/
select map_breed('SL') as breed