Sql 仅从Postgres JSONB对象数组中访问(并计数)对象值
我在Postgres数据库中有一个JSONB列。我存储了一个JSON对象数组,每个对象都有一个键值对。我相信我本可以设计得更好,但现在我还是坚持这个Sql 仅从Postgres JSONB对象数组中访问(并计数)对象值,sql,postgresql,jsonb,Sql,Postgresql,Jsonb,我在Postgres数据库中有一个JSONB列。我存储了一个JSON对象数组,每个对象都有一个键值对。我相信我本可以设计得更好,但现在我还是坚持这个 id | reviews ------------------ 1 | [{"apple": "delicious"}, {"kiwi": "not-delicious"}] 2 | [{"orange": "not-delicious"}, {"pair": "not-delicious"}] 3 | [{"grapes": "delici
id | reviews
------------------
1 | [{"apple": "delicious"}, {"kiwi": "not-delicious"}]
2 | [{"orange": "not-delicious"}, {"pair": "not-delicious"}]
3 | [{"grapes": "delicious"}, {"strawberry": "not-delicious"}, {"carrot": "delicious"}]
假设此表名为任务
。虽然每个对象中的关键点都是不可预测的,但值是可预测的。对于每一行,我想知道reviews
数组中“美味”和“不美味”值的数量
编辑以澄清:
我正在查找上表中每个id
/行的美味/不美味计数。所需输出示例:
id | delicious | not_delicious
-------------------------------
1 | 1 | 1
2 | 0 | 2
3 | 2 | 1
假设r是您的桌子:
so=# select * from r;
reviews
-------------------------------------------------------------------------------------
[{"apple": "delicious"}, {"kiwi": "not-delicious"}]
[{"orange": "not-delicious"}, {"pair": "not-delicious"}]
[{"grapes": "delicious"}, {"strawberry": "not-delicious"}, {"carrot": "delicious"}]
(3 rows)
然后:
我使用ctid作为行标识符,因为我没有其他列,也不需要长时间的reviews
很明显,每行的delicious的聚合:
so=# with j as (select jsonb_array_elements(reviews) a, r, ctid from r)
select ctid, a->>jsonb_object_keys(a), count(*) from j group by a->>jsonb_object_keys(a),ctid;
ctid | ?column? | count
-------+---------------+-------
(0,1) | delicious | 1
(0,3) | delicious | 2
(0,1) | not-delicious | 1
(0,2) | not-delicious | 2
(0,3) | not-delicious | 1
(5 rows)
更新后的帖子
so=# with j as (select jsonb_array_elements(reviews) a, r, ctid from r)
, n as (
select ctid,a->>jsonb_object_keys(a) k from j
)
, ag as (
select ctid
, case when k = 'delicious' then 1 else 0 end deli
, case when k = 'not-delicious' then 1 else 0 end notdeli
from n
)
select ctid, sum(deli) deli, sum(notdeli) notdeli from ag group by ctid;
ctid | deli | notdeli
-------+------+---------
(0,1) | 1 | 1
(0,2) | 0 | 2
(0,3) | 2 | 1
(3 rows)
我会澄清我的问题,因为这不是我想要的。很抱歉,但感谢您的回复。@user94154我得到了其他结果编号,但它们在我看来是正确的,以便更新并捕获我的错误。我更新了我的帖子来解决这个问题。如果答案可以接受,请接受和/或投赞成票
so=# with j as (select jsonb_array_elements(reviews) a, r, ctid from r)
, n as (
select ctid,a->>jsonb_object_keys(a) k from j
)
, ag as (
select ctid
, case when k = 'delicious' then 1 else 0 end deli
, case when k = 'not-delicious' then 1 else 0 end notdeli
from n
)
select ctid, sum(deli) deli, sum(notdeli) notdeli from ag group by ctid;
ctid | deli | notdeli
-------+------+---------
(0,1) | 1 | 1
(0,2) | 0 | 2
(0,3) | 2 | 1
(3 rows)