【发布时间】:2019-09-24 09:36:19
【问题描述】:
所以我有一个 postgres 数据库,其中有一个名为 jsonb 的字段 details:
sensor | details
------------------
A | [{"direction":"up", "result": 1.0}, {"direction":"up", "result": 2.0}]
B | [{"direction":"up", "result": 3.0}, {"direction":"down", "result": 4.0}]
B | [{"direction":"up", "result": 5.0}, {"direction":"up", "result": 6.0}, {"direction":"down", "result": 7.0}]
A | [{"direction":"down", "result": 8.0}, {"direction":"left", "result": 9.0}]
我现在需要按传感器分组的所有上行记录和下行记录的result 的总和。
所以我的查询应该是这样的:
sensor | up_sum | down_sum
---------------------------
A | 3.0 | 8.0
B | 14.0 | 11.0
我需要以某种方式:
- 循环遍历 details 数组对象
- 按
up和down过滤 - 然后将每个传感器的这些记录的结果相加
我猜子查询是这样做的唯一方法(对吗?)。我找到了the postgres documentation on how to handle json,于是开始循环遍历对象:
SELECT jsonb_array_elements(details)
FROM table;
这只是给了我一个对象列表。所以我现在需要按up 过滤,我认为我需要使用json_to_recordset()。我试过这个:
SELECT *
FROM json_to_recordset('[{"direction":"up", "result": 1.0}, {"direction":"up", "result": 2.0}, {"direction":"down", "result": 3.0}]') as x(direction varchar, result float)
WHERE direction = 'up';
结果是预期的
direction | result
------------------
up | 1
up | 2
现在让我们总结一下:
SELECT SUM(result) as up_sum
FROM json_to_recordset('[{"direction":"up", "result": 1.0}, {"direction":"up", "result": 2.0}, {"direction":"down", "result": 3.0}]') as x(direction varchar, result float)
WHERE direction = 'up';
太好了,这行得通!
现在我将它插入到我之前的查询中:
SELECT
jsonb_array_elements(details),
(
SELECT SUM(result)
FROM json_to_recordset('[{"direction":"up", "result": 1.0}, {"direction":"up", "result": 2.0}, {"direction":"down", "result": 3.0}]') as x(direction varchar, result float)
WHERE direction = 'up'
) as up_sum
FROM table;
好的,这也很好用。
现在我只需要在json_to_recordset() 中使用jsonb_array_elements(details) 的结果(或者实际上jsonb_to_recordset() 用于jsonb 字段)。所以我然后运行了这个:
SELECT
jsonb_array_elements(details),
(
SELECT SUM(result)
FROM jsonb_to_recordset(jsonb_array_elements(details)) as x(direction varchar, result float)
WHERE direction = 'up'
) as up_sum
FROM table;
不幸的是,这给出了一个错误:
错误:返回集合的函数必须出现在 FROM 的顶层
谁能提示我正确的方向?
【问题讨论】:
-
您的“将其插入我以前的”查询不起作用。是不是少了一个逗号? dbfiddle.uk/…
-
@S-Man - 好点。我更正了。
标签: sql postgresql