开发者

Is it possible to use CASE with WHERE?

开发者 https://www.devze.com 2023-01-05 10:19 出处:网络
Trying to do this: SELECT CASE WHEN field = true THEN one 开发者_StackOverflow* another ELSE one END as case_field

Trying to do this:

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

and receive an error that case_field doesn't exist.

Is it possible to do this without duplicating CASE ?


Looks like PostgresSQL supports 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

You might want to check that it doesn't have any adverse affect on the execution plan.


Use a temporary table:

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

精彩评论

暂无评论...
验证码 换一张
取 消