我有一堆动态调查结果存储在一个带有JSON列的表中,如下所示:
{"regional":"never","local":"sometimes","personal":"often","bike":"field_4","walk":"field_5","carpool":"field_4","carshare":"often","rideshare":"sometimes"}
键是整个数据集中动态存在的值。我需要找到一种有效的方法来聚合密钥并计算相关结果。该数据代表了李克特量表调查问题,即
"你多久去一个公交车站?不经常,有时,经常"
我想生成的结果数据集是:
{
"regional": { "sometimes": 20, "often": 10, "never": 5 },
"bike": { "sometimes": 20, "often": 10, "never": 5 }
"walk": { "sometimes": 20, "often": 10, "never": 5 }
}
我已尝试将JSON_EACH分解为键/值对,但我现在无法汇总密钥和潜在结果的频率。这就是我到目前为止所做的:
SELECT
json_data.key,
json_data.value
FROM
"SubmissionData" AS sd,
JSON_EACH_TEXT(sd.data) AS json_data
WHERE
sd.key = 'transit'
虽然在这里肯定遇到了障碍。
感谢。
答案 0 :(得分:1)
使用json_object_agg()
,例如:
with my_table(data) as (
values
('{"regional":"never","local":"sometimes","personal":"often"}'::json),
('{"regional":"often","local":"sometimes","personal":"often"}'::json)
)
select json_object_agg(key, vals)
from (
select key, json_object_agg(value, count) vals
from (
select key, value, count(*)
from
my_table,
json_each_text(data)
group by 1, 2
) s
group by 1
) s;
json_object_agg
------------------------------------------------------------------------------------------------------------
{ "regional" : { "never" : 1, "often" : 1 }, "personal" : { "often" : 2 }, "local" : { "sometimes" : 2 } }
(1 row)