PostgreSQL: return message after count = 0

时光怂恿深爱的人放手 提交于 2020-01-06 20:11:17

问题


I have maybe easy question, but I'm completely stucked.

I have script

SELECT COALESCE(COUNT(id), 0) as MyFiels from table

It works fine and when I have zero value it shows 0.

But I want that instead of 0, I can see one line = "NO RESULTS" for example.

I tried:

SELECT COALESCE(to_char(COUNT(id), 'NO RESULT')) as MyFiels from table

And PostgreSQL shows error message:

ERROR: "E" is not supported
SQL state: 0A000

Where I'm incorrect? Any ideas?


回答1:


I see what is the error, you are trying to use coalesce to convert 0 to string, and coalesce convert null to something. You need use a CASE

SELECT  CASE WHEN COUNT(*)  = 0 THEN 'NO RESULT'
             ELSE CAST(COUNT(*) as TEXT)
        END as field
FROM Table


来源:https://stackoverflow.com/questions/34771537/postgresql-return-message-after-count-0

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