我正在使用jsonb
列的Postgres表。我已经能够创建一个记录集来将json转换为jsonb对象的行。我正在努力将timestamp
从UNIX转换为可读的时间戳。
这是jsonb
对象在将timestamp
存储为UNIX时的样子:
{
"signal": [
{
"id": "e80",
"on": true,
"unit": "sample 1",
"timestamp": 1521505355
},
{
"id": "97d",
"on": false,
"unit": "sample 2",
"timestamp": 1521654433
},
{
"id": "97d",
"on": false,
"unit": "sample 3",
"timestamp": 1521654433
}
]
}
理想情况下,我希望它看起来像这样但是timestamp
id | on | unit | timestamp
---+------+----------+--------------------------
e80|true | sample 1 | 2018-03-20 00:22:35+00:00
97d|false | sample 2 | 2018-03-21 17:47:13+00:00
97d|false | sample 3 | 2018-03-21 17:47:13+00:00
这是我到目前为止返回列的预期值但是为timestamp
列提供错误
select b.*
from device d
cross join lateral jsonb_to_recordset(d.events->'signal') as
b("id" integer, "on" boolean, "unit" text, "timestamp" timestamp)
timestamp
数据类型正在抛出错误。
[22008]错误:日期/时间字段值超出范围
非常感谢任何有关将timestamp
从UNIX转换为实际时间戳的帮助或建议。
答案 0 :(得分:1)
您可以在列定义列表中将其指定为INTEGER
,然后使用TIMESTAMP
将其转换为TO_TIMESTAMP
此外,您尝试定义的id
不能是integer
。
查询1 :
SELECT b.id
,b.ON
,b.unit
,to_timestamp("timestamp") AS "timestamp"
FROM device d
CROSS JOIN lateral jsonb_to_recordset(d.events -> 'signal')
AS b("id" TEXT, "on" boolean, "unit" TEXT, "timestamp" INT)
<强> Results 强>:
| id | on | unit | timestamp |
|-----|-------|----------|----------------------|
| e80 | true | sample 1 | 2018-03-20T00:22:35Z |
| 97d | false | sample 2 | 2018-03-21T17:47:13Z |
| 97d | false | sample 3 | 2018-03-21T17:47:13Z |