在值为true的postgresql表中获取jsonb对象的所有键

问题描述

我有一个customersname列的postgresql表。{p>

features包含jsonb对象,例如features

我想要得到的是{"featureA": true,"featureB": false,"featureC":true}中的那些键的数组,其中每个features的值都为true,例如:

name

我从this post中学到了

name      | features
----------|---------------------
customerA | [featureA,featureC]
customerB | [featureB,featureC]

如何获得正确的键,但是如何为我的表SELECT key FROM jsonb_each() WHERE value = jsonb 'true' 做到这一点?

类似

customers

返回SELECT array_agg(key) FROM jsonb_each((select features from customers)) WHERE value = jsonb 'true'

任何帮助将不胜感激。

解决方法

您正在描述横向连接:

select c.name,x.keys
from customers c
cross join lateral (
    select array_agg(x.key) keys
    from jsonb_each(c.features) x
    where x.value = jsonb 'true'
) x
,

也可以像这样在select子句中使用jsonb_each()

select
    x.name,json_agg(x.feature_name) as features
from (
    select
        c.name,row_to_json(jsonb_each(c.features))->>'key' as feature_name,(row_to_json(jsonb_each(c.features))->>'value')::bool as value
    from customers c
) as x
where x.value
group by x.name;