在Postgres v9.6.15中,我需要使用某些键的文本模式获取所有值的SUM。
例如,具有包含 4 行的表"TABLE1":
|group |col1
======================================
Row #1:|group1 |{ "json_key1.id1" : 1 }
Row #2:|group1 |{ "json_key1.id2" : 1 }
Row #3:|group1 |{ "json_key2.idX" : 1 }
Row #4:|group1 |{ "not_me" : 2 }
我想使用键的第一部分("json_key1"和"json_key2"(的模式获取 int 值,并使用 CASE 块将它们全部求和,如下所示:
SELECT table1.group as group,
COALESCE(sum(
CASE
WHEN table1.col1 = 'col1_val1' THEN (table1.json_col->>'json_key1.%')::bigint
WHEN table1.col1 = 'col1_val2' THEN (table1.json_col->>'json_key2.%')::bigint
ELSE 0::bigint
END), 0)::bigint AS my_result
FROM table1 as table1
GROUP BY table1.group;
我需要"my_result"看起来像:
|group |my_result
======================================
Row #1:|group1 |3
有没有办法使用正则表达式或类似的东西收集值。不确定我是否正在检查正确的文档(https://www.postgresql.org/docs/9.6/functions-json.html(,但我没有找到任何可以帮助我实现上述目标的东西,或者如果这实际上可行。
在横向连接中使用jsonb_each_text()
从 JSON 对象获取(key, value)
对:
select
group_col as "group",
coalesce(sum(case when key like 'json_k%' then value::numeric end), 0) as my_result
from table1
cross join jsonb_each_text(col1)
group by group_col
Db<>小提琴。