微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决从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;

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。