我正在使用具有 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 转换为实际时间戳的任何帮助或建议。
最佳答案
您可以在列定义列表中将其指定为INTEGER
,然后使用TO_TIMESTAMP
将其转换为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 |
关于arrays - Postgres jsonb 将记录集从 UNIX 转换为时间戳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49473067/