现在我有以下查询:
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?)。
答案 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"