问题
How can I translate the DECODE expression in Postgres?
MAX(DECODE(r.name,'AREA_SEC_TRANVERSAL',r.value,NULL)) AREA
I found the following type, but i did not know how "MAX" can fit in this case.
CASE search-expression
WHEN expression [, expression [ ... ]] THEN
statements
[ WHEN expression [, expression [ ... ]] THEN
statements
... ]
[ ELSE
statements ]
END CASE;
回答1:
A common translation would use case a expression:
MAX(CASE WHEN r.name = 'AREA_SEC_TRANVERSAL' THEN r.value END) as AREA
In fact, the general replacement for DECODE() is CASE, which is the SQL standard for conditional logic -- I would recommend CASE even in databases that support DECODE().
However, Postgres supports the standard SQL filter operator. I would recommend using this instead:
MAX(r.value) FILTER (WHERE r.name = 'AREA_SEC_TRANVERSAL') as AREA
I find this easier to follow (perhaps now that I'm used to it). More importantly, it gives the optimizer better options for improving performance.
回答2:
You can just keep max as is:
MAX(CASE
WHEN r.name = 'AREA_SEC_TRANVERSAL'
THEN r.value
END) AREA
or
MAX(CASE r.name
WHEN 'AREA_SEC_TRANVERSAL'
THEN r.value
ELSE null
END) AREA
来源:https://stackoverflow.com/questions/58185876/translating-decode-in-postgres