可以在WHERE中使用CASE吗?

时间:2010-06-28 11:47:32

标签: sql postgresql

尝试这样做:

SELECT CASE WHEN field = true THEN one * another ELSE one END as case_field 
FROM table WHERE case_field >= 9000

并收到case_field不存在的错误。

是否可以在不重复CASE的情况下执行此操作?

2 个答案:

答案 0 :(得分:7)

看起来PostgresQL支持derived tables

SELECT * FROM 
(
SELECT CASE WHEN field = true THEN one * another ELSE one END as case_field 
FROM table 
) AS derived
WHERE case_field >= 9000

您可能想检查它对执行计划没有任何不利影响。

答案 1 :(得分:0)

使用临时表:

SELECT *
FROM (
     SELECT 
        CASE WHEN field = true THEN one * another
        ELSE one
        END as case_field 
        FROM table
     ) a
 WHERE a.case_field >= 9000