【问题标题】:Integrate separate year, month, day, hour, minute and second columns as a single timestamp column将单独的年、月、日、小时、分钟和秒列集成为单个时间戳列
【发布时间】:2012-11-06 14:08:37
【问题描述】:

我的数据集包含单独的年、月、日、小时、分钟和第二列,如下所示,用空格分隔:

+-------------------+
|2007|09|28|21|14|06|
|2007|09|28|21|14|06|
|2007|09|28|21|14|06|
|2007|09|28|21|14|06|
|2007|09|28|21|14|06|
+-------------------+

我想将它们集成为时间戳数据类型下的单个列。 我在时间戳数据类型中创建了一个新列,并通过以下代码更新该列:

 Update s2
 set dt = year || '-' || month  || '-' || day
               || ' ' || hour  || ':' || min  || ':' || second 

但我遇到了以下错误:

ERROR:  column "dt" is of type timestamp without time zone but expression is of type text
LINE 1:  Update temp set dt= year || '-' || month  || '-' || day  ||...
                             ^
HINT:  You will need to rewrite or cast the expression.

********** Error **********

ERROR: column "dt" is of type timestamp without time zone but expression is of type text
SQL state: 42804
Hint: You will need to rewrite or cast the expression.
Character: 22

此外,我可以通过varchar data-type 进行集成。

【问题讨论】:

  • column "dt" is of type timestamp without time zone but expression is of type text, You will need to rewrite or cast the expression. 这似乎是个好建议。你试过了吗?
  • @Mat,是的,我已经尝试过了,并将年、月、日定义为日期数据类型,将小时、分钟和秒定义为时间数据类型,然后我执行了命令,但上述错误是观察到。

标签: postgresql types timestamp


【解决方案1】:

您需要从texttimestamp without time zone 的简单转换:

(expression)::timestamp without time zone

例如:

Update s2 set dt = (year || '-' || month  || '-' || day  || ' ' || hour  || ':' || min  || ':' || second)::timestamp without time zone

【讨论】:

  • timestamp 默认为timestamp without time zone
【解决方案2】:

表达式的结果

year || '-' || month  || '-' || day || ' ' || hour  || ':' || min  || ':' || second 

不是时间戳,而是纯文本。错误消息只是告诉您,text 类型不适合 dt 列的类型。

您必须像这样转换 complete 表达式:

(year || '-' || month  || '-' || day || ' ' || hour  || ':' || min  || ':' || second)::timestamp

【讨论】:

    【解决方案3】:

    您得到了解释错误的答案:您需要将 text 显式转换为 timestamp

    但是,正确的解决方案是使用to_timestamp()

    UPDATE s2
    SET dt = to_timestamp(year || '-' || month  || '-' || day || ' '
                               || hour  || ':' || min  || ':' || second
                         ,'YYYY-MM-DD hh24:mi:ss');
    

    为什么?
    普通转换 'text'::timestamp 取决于日期/时间格式的本地设置,并且可能在一个安装中有效,但在另一个 PostgreSQL 安装中“突然”失败。给定的语句保证工作,独立于datestyle 设置和语言环境。

    嗯,准确地说,示例中的模式 ('YYYY-MM-DD hh24:mi:ss') 匹配 ISO 8601(SQL 标准),这对 任何 语言环境都有效。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-20
      • 2020-10-18
      • 2011-06-10
      • 1970-01-01
      • 2011-09-06
      • 1970-01-01
      • 2016-06-06
      相关资源
      最近更新 更多