Here is my query:
select col1, col2, (<a fairly complex query> as col3) from <a table>
<a fairly complex query>
may return NULL
, in which case I want to set col3
to col2
. I know I could do this with a CASE
statement:
select col1, col2,
CASE WHEN (<a fairly complex query>) is NULL col2
ELSE (<a fairly complex query>) END AS col3
from <a table>
However, that approach executes <a fairly complex query>
twice. What are some options if I only want to execute <a fairly complex query>
once?
You could use subquery and COALESCE
:
SELECT col1, col2, COALESCE(col3, col2) AS col3
FROM (select col1, col2, (<a fairly complex query>) as col3
from <a table>) AS sub;
Without subquery:
SELECT col1, col2, COALESCE(<a fairly complex query>, col2) AS col3
FROM <a table>;
与其他答案类似,但是不需要子查询:
select col1, col2, COALESCE(<a fairly complex query>, col2) AS col3 from <a table>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.