【问题标题】:combine year, month, day, hour, minute and second fields to a one column at "TIMESTAMP" in SQL将年、月、日、小时、分钟和秒字段组合到 SQL 中“TIMESTAMP”处的一列
【发布时间】:2012-10-10 07:55:41
【问题描述】:

我有一个表格,其中分别包含以下列: 年、月、日、时、分、秒

如何将它们组合为“TI​​MESTAMP”格式的单个列?

提前谢谢你。

【问题讨论】:

  • 将其他答案放在一起,使用它们为时间戳创建一个新列并将其更新为具有真正的时间戳,然后删除原始列。然后您可以在以后轻松地提取()您想要的片段,并且在其余时间您将拥有一个实际的时间戳。这是原始设计师太聪明的时候之一。

标签: postgresql timestamp


【解决方案1】:

从 Postgres 9.4 开始,这变成了a lot easier

select make_timestamp(year, month, day, hour, minute, second) as ts_value
from the_table;

这假定所有列都是整数(second 除外,它也可能是双精度)

要创建date,请使用make_date(),对于time 值,请使用make_time()

【讨论】:

    【解决方案2】:

    只需使用连接并转换为时间戳。 这是一个例子:

    CREATE TABLE test (year integer, month integer, day integer,
                       hour integer, min integer,   sec integer);
    
    INSERT INTO  test (year, month, day, hour, min, sec)
               VALUES (2012,    10,  11,   01,  10,  35);
    
    SELECT (year::text || '-' || month::text || '-' || day::text || ' '
         || hour::text || ':' || min::text   || ':' || sec::text)::timestamp
    FROM test
    
    "timestamp"
    "10/11/2012 1:10:35 AM"
    

    【讨论】:

      【解决方案3】:
        SELECT year || '-' || month  || '-' || day  || ' ' || hour  || ':' || minute  || ':' || second FROM table_name
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-08-24
        • 1970-01-01
        • 2012-05-25
        • 2011-07-26
        • 2011-06-10
        • 1970-01-01
        • 2012-11-06
        相关资源
        最近更新 更多