如何根据此列将SELECT输出列转换为任意值?

时间:2014-07-07 11:42:00

标签: sql postgresql

现在我有以下查询:

SELECT "type" AS "modifiedType"
FROM "Table" 
WHERE "type" = 'type1' OR "type" = 'type2'

我想要的是像这样返回modifiedType

if "type" = 'type1' then 'modifiedType1'
else if "type" = 'type2' then 'modifiedType2'

所以我只想根据原始列值修改另一个值的列值。 键入ENUM中的列而不是字符串。

我正在使用Postgres 9.3(或9.4?)。

3 个答案:

答案 0 :(得分:4)

使用CASE声明:

select type,
       case
         when type = 'type1' then 'modifiedType1'
         when type = 'type2' then 'modifiedType2'
         else type
       end as modifiedType
from the_table
WHERE type in ('type1', 'type2')

顺便说一下:type不是列的好名字

答案 1 :(得分:2)

对于单个条件,simple CASE对于多个替代方案更有效:

SELECT CASE type
          WHEN 'type1' THEN 'modifiedType1'
          WHEN 'type2' THEN 'modifiedType2'
          ELSE type
       END AS modified_type
FROM   tbl;

BTW,对于许多替代方案,编写WHERE这样的句子的时间更短:

WHERE type IN ('type1', 'type2', 'type3', ...)

甚至

WHERE type = ANY('{type1, type2, type3, ...}')

所有变体都在内部翻译为相同的 OR列表。

答案 2 :(得分:1)

您可能想要使用案例

SELECT
CASE
    WHEN "type" = 'type1'
    THEN 'modifiedType1'
    ELSE 'modifiedType2'
END AS "modifiedType"
FROM "Table"