SQL 从 PostgreSQL 中选择日期(时间戳)作为字符串(字符),注意 NULL 值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15990344/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 14:49:58  来源:igfitidea点击:

Select date (timestamp) from PostgreSQL as string (char), beware of NULL value

sqlpostgresqlselectpostgresql-9.1

提问by Katie

I want to select a date (my column is a timestamp type). But when in column is a NULL date, I want to return an empty string. How to do this? I wrote this:

我想选择一个日期(我的列是时间戳类型)。但是当列是一个空日期时,我想返回一个空字符串。这该怎么做?我是这样写的:

SELECT
   CASE WHEN to_char(last_post, 'MM-DD-YYYY HH24:MI:SS') IS NULL THEN ''
      ELSE to_char(last_post, 'MM-DD-YYYY HH24:MI:SS') AS last_post END
   to_char(last_post, 'MM-DD-YYYY HH24:MI:SS') AS last_post, content
FROM topic;

But it shows me some errors, dont really know why:

但它显示了一些错误,不知道为什么:

ERROR:  syntax error at or near "as"
LINE 1: ...ELSE to_char(last_post, 'MM-DD-YYYY HH24:MI:SS') AS last_po...
                                                            ^

回答by Nerdwood

Using the COALESCE()function is the nicest approach, as it simply swaps in a substitute value in the case of a NULL. Readability is improved greatly too. :)

使用该COALESCE()函数是最好的方法,因为它只是在 NULL 的情况下交换一个替代值。可读性也大大提高。:)

SELECT COALESCE(to_char(last_post, 'MM-DD-YYYY HH24:MI:SS'), '') AS last_post, content FROM topic;

回答by Jerry

You're putting your ASwithin the case?

你把你的AS放在案子里?

Try:

尝试:

SELECT
   CASE WHEN last_post IS NULL THEN ''
     ELSE to_char(last_post, 'MM-DD-YYYY HH24:MI:SS') END AS last_post,
   content
FROM topic;

I haven't tried the query though.

我还没有尝试过查询。

回答by Clodoaldo Neto

select coalesce(to_char(last_post, 'MM-DD-YYYY HH24:MI:SS'), '') as last_post, content
from topic;