Translating DECODE in Postgres

柔情痞子 提交于 2019-12-11 19:09:02

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!