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

extract data from sql query json format

我有一个 table sensor_measurements 列测量和 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", "units": "ppm", "concentration": 0.002, "temporal_resolution": "1h"},
  {"name": "TEMP", "units": "celsius", "concentration": 28, "temporal_resolution": "1h"},
   {"name": "HUM", "units": "percent", "concentration": 38, "temporal_resolution": "1h"}, 
   {"name": "PM10", "units": "µg/m3", "concentration": 8, "temporal_resolution": "1h"},
    {"name": "PM25", "units": "µg/m3", "concentration": 7, "temporal_resolution": "1h"}]
    
October 22, 2019, 10:00 PM
[{"name": "NO", "units": "ppm", "concentration": 0.002205, "temporal_resolution": "1h"},
 {"name": "NO2", "units": "ppm", "concentration": 0.008, "temporal_resolution": "1h"},
  {"name": "TEMP", "units": "celsius", "concentration": 28, "temporal_resolution": "1h"}, 
  {"name": "HUM", "units": "percent", "concentration": 38, "temporal_resolution": "1h"}, 
  {"name": "PM10", "units": "µg/m3", "concentration": 9, "temporal_resolution": "1h"}, 
  {"name": "PM25", "units": "µg/m3", "concentration": 8, "temporal_resolution": "1h"}]
  
October 22, 2019, 11:00 PM
[{"name": "NO", "units": "ppm", "concentration": 0.002209, "temporal_resolution": "1h"},
 {"name": "NO2", "units": "ppm", "concentration": 0.004, "temporal_resolution": "1h"},
  {"name": "TEMP", "units": "celsius", "concentration": 28, "temporal_resolution": "1h"}, 
  {"name": "HUM", "units": "percent", "concentration": 38, "temporal_resolution": "1h"}, 
  {"name": "PM10", "units": "µg/m3", "concentration": 8, "temporal_resolution": "1h"}, 
  {"name": "PM25", "units": "µg/m3", "concentration": 7, "temporal_resolution": "1h"}]
  
October 23, 2019, 12:00 AM
[{"name": "NO", "units": "ppm", "concentration": 0.002125, "temporal_resolution": "1h"},
{"name": "NO2", "units": "ppm", "concentration": 0.004, "temporal_resolution": "1h"}, 
{"name": "TEMP", "units": "celsius", "concentration": 28, "temporal_resolution": "1h"}, 
{"name": "HUM", "units": "percent", "concentration": 39, "temporal_resolution": "1h"}]


October 23, 2019, 4:00 PM
[{"name": "NO", "units": "ppm", "concentration": 0.004563, "temporal_resolution": "1h"}, 
{"name": "TEMP", "units": "celsius", "concentration": 34, "temporal_resolution": "1h"}, 
{"name": "HUM", "units": "percent", "concentration": 28, "temporal_resolution": "1h"}]

我想提取时间戳,pollutant和它的值(浓度!

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

数据库类型为 PostgreSQl(在 metabase.com 中)

我是在 postgres 上做的。
首先你必须有类型代表你的数据:

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

接下来可以使用json作为加入table:

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