我有一张表:
CREATE TABLE stats
(
item character varying,
data jsonb
);
it contains values like
ITEM DATA
test1 [{"id":"1", "country":"UK"},{"id":"2", "country":"INDIA"}]
test2 [{"id":"1", "country":"US"},{"id":"4", "country":"CHINA"},{"id":"5", "country":"CHINA"}]
我需要获得一些不同的json对象,其中country是' CHINA'和项目是'%test%&#39 ;; 在这种情况下,输出应为2,即[{" id":" 4"," country":" CHINA"}, {" id":" 5"," country":" CHINA"}]
我使用以下查询
SELECT * FROM stats t
WHERE ( data @> '[{"country":"CHINA"}]')
and t.item ilike '%test%';
output : [{"id":"1", "country":"US"},{"id":"4", "country":"CHINA"},{"id":"5", "country":"CHINA"}]
我该怎么办才能得到一系列具有“中国”的物品。作为国家?
答案 0 :(得分:0)
使用jsonb_array_elements()
获取单个json对象,过滤它们并使用jsonb_agg()
聚合成json数组。
select item, jsonb_agg(obj)
from stats, jsonb_array_elements(data) obj
where obj->>'country' = 'CHINA'
group by 1;