Sql 如何基于该列将SELECT output列转换为任意值?
目前我有以下疑问:Sql 如何基于该列将SELECT output列转换为任意值?,sql,postgresql,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' WHERE type IN ('type1', 'type2', 'typ
SELECT "type" AS "modifiedType"
FROM "Table"
WHERE "type" = 'type1' OR "type" = 'type2'
我要返回的是modifiedType
,如下所示:
if "type" = 'type1' then 'modifiedType1'
else if "type" = 'type2' then 'modifiedType2'
WHERE type IN ('type1', 'type2', 'type3', ...)
所以我只想在原始列值的基础上用另一个值修改列值。
在ENUM
中键入列,而不是字符串
我使用的是Postgres 9.3(或9.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
不是一个很好的列名称您可能需要使用case
SELECT
CASE
WHEN "type" = 'type1'
THEN 'modifiedType1'
ELSE 'modifiedType2'
END AS "modifiedType"
FROM "Table"
对于单个条件,使用多个备选方案时,A的效率更高:
SELECT CASE type
WHEN 'type1' THEN 'modifiedType1'
WHEN 'type2' THEN 'modifiedType2'
ELSE type
END AS modified_type
FROM tbl;
顺便说一句,对于许多备选方案,编写WHERE
子句的时间更短,如下所示:
if "type" = 'type1' then 'modifiedType1'
else if "type" = 'type2' then 'modifiedType2'
WHERE type IN ('type1', 'type2', 'type3', ...)
甚至
WHERE type = ANY('{type1, type2, type3, ...}')
所有变体都在内部转换为相同的或列表