在case语句中使用select语句中的参数

时间:2018-07-06 08:15:44

标签: sql postgresql column-alias

我有以下查询

SELECT product.*,
(SELECT bid FROM server1 WHERE product_id = product.id) AS bid1,
(SELECT bid FROM server2 WHERE product_id = product.id) AS bid2,
CASE
    WHEN bid1 > bid2 THEN '1 wins'
    WHEN bid2 > bid1 THEN '2 wins'
    ELSE 'undecided'
END AS bid_status
FROM product
WHERE id= $1

此查询在CASE语句中引发错误,指出bid1列不存在。如何将子查询作为case语句的变量传递?

1 个答案:

答案 0 :(得分:2)

范围问题。首先将查询包装为派生表:

select dt.*
    CASE
        WHEN bid1 > bid2 THEN '1 wins'
        WHEN bid2 > bid1 THEN '2 wins'
        ELSE 'undecided'
    END AS bid_status
from
(
SELECT product.*,
    (SELECT bid FROM server1 WHERE product_id = product.id) AS bid1,
    (SELECT bid FROM server2 WHERE product_id = product.id) AS bid2,
FROM product
WHERE id= $1
) dt