从sql查询json格式中提取数据

问题描述

我有一个表 sensor_measurements 和列measurement和measure_at(时间戳)

 select measured_at,pollutants
    from sensor_measurements;

给出:

October 22,2019,9:00 PM
[{"name": "NO","units": "ppm","concentration": 0.002161,"temporal_resolution": "1h"},{"name": "NO2","concentration": 0.002,{"name": "TEMP","units": "celsius","concentration": 28,{"name": "HUM","units": "percent","concentration": 38,{"name": "PM10","units": "µg/m3","concentration": 8,{"name": "PM25","concentration": 7,"temporal_resolution": "1h"}]
    
October 22,10:00 PM
[{"name": "NO","concentration": 0.002205,"concentration": 0.008,"concentration": 9,"temporal_resolution": "1h"}]
  
October 22,11:00 PM
[{"name": "NO","concentration": 0.002209,"concentration": 0.004,"temporal_resolution": "1h"}]
  
October 23,12:00 AM
[{"name": "NO","concentration": 0.002125,"concentration": 39,"temporal_resolution": "1h"}]


October 23,4:00 PM
[{"name": "NO","concentration": 0.004563,"concentration": 34,"temporal_resolution": "1h"}]

我想提取时间戳 pollutant 及其值(浓度!

理想情况下,我想创建包含时间戳、污染物和值的三列,以便下载为 csv。

数据库类型为 Postgresql(在 Metabase.com 中)

解决方法

我是在 postgres 上做的。
首先,您必须让类型代表您的数据:

CREATE TYPE x as ("name" VARCHAR,"units" VARCHAR,"concentration" FLOAT,"temporal_resolution" VARCHAR );

接下来,您可以使用 json 作为连接表:

SELECT measured_at,name,concentration
FROM sensor_measurements
LEFT JOIN LATERAL json_populate_recordset(null::x,pollutants::json) ON true;