4

私のデータセットには、スペースで区切られた次のような年、月、日、時、分、秒の列が含まれています。

+-------------------+
|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さらに、データ型ごとに統合を実行できます。

4

3 に答える 3

5

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 標準) に一致します。

于 2012-11-18T13:55:07.067 に答える
2

textからへの単純なキャストが必要ですtimestamp without time zone:

(expression)::timestamp without time zone

例えば:

Update s2 set dt = (year || '-' || month  || '-' || day  || ' ' || hour  || ':' || min  || ':' || second)::timestamp without time zone
于 2012-11-18T13:47:09.290 に答える
1

式の結果

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

タイムスタンプではなくプレーンテキストです。エラー メッセージは、text型が列の型に適していないことを示していdtます。

次のように完全な式をキャストする必要があります。

(year || '-' || month  || '-' || day || ' ' || hour  || ':' || min  || ':' || second)::timestamp
于 2012-11-18T13:48:55.080 に答える