PostgreSQL - 如何用任何字符串替换空字段?

时间:2013-12-17 09:29:56

标签: postgresql null coalesce

我正在尝试使用我想要的任何字符串替换一些空(NULL)字段,这些字段是我查询的结果。这些空字段放在“没有时区的时间戳”列中。所以我尝试使用COALESCE函数,但没有结果(我收到错误:时间戳的输入语法无效:“any_string”:

select column1, coalesce(date_trunc('seconds', min(date)), 'any_string') as column2

可能出现什么问题?

表:

╔════╦═════════════════════╦═════════════════════╗
║ id ║        date         ║        date2        ║
╠════╬═════════════════════╬═════════════════════╣
║  1 ║ 2013-12-17 13:54:59 ║ 2013-12-17 09:03:31 ║
║  2 ║ 2013-12-17 13:55:07 ║ 2013-12-17 09:59:11 ║
║  3 ║ 2013-12-17 13:55:56 ║ empty field         ║
║  4 ║ 2013-12-17 13:38:37 ║ 2013-12-17 09:14:01 ║
║  5 ║ 2013-12-17 13:54:46 ║ empty field         ║
║  6 ║ 2013-12-17 13:54:46 ║ empty field         ║
║  7 ║ 2013-12-17 13:55:40 ║ empty field         ║
╚════╩═════════════════════╩═════════════════════╝

示例查询:

select q1.id, q2.date, q3.date2
from (select distinct id from table1) q1
left join (select id, date_trunc('seconds', max(time)) as date from table2 where time::date = now()::date group by id) q2 on q1.id = q2.id
left join (select id, date_trunc('seconds', min(time2)) as date2 from table1 where time2:date = now()::date group by id) q3 on q1.id = q3.id
order by 1

问题是用我想象的任何字符串替换上面的那些空字段。

3 个答案:

答案 0 :(得分:1)

date_trunc() function会返回timestamp,因此您无法在同一列中插入any_string之类的字符串。

您必须选择一种格式convert the resulting date to string,但当然它不再可用作日期。

答案 1 :(得分:1)

您可以使用::text

简单地将时间戳投射到文本中
select column1, coalesce(date_trunc('seconds', min(date))::text, 'any_string') as column2

答案 2 :(得分:-1)

coalesce函数仅适用于整数数据类型。它不适用于任何其他数据类型。

在一些情况下,我曾使用coalesce语法将varchar数据类型转换为_columnName_ :: integer函数内的整数。 但在你的情况下,我不认为时间戳将被转换为整数数据类型。