gpt4 book ai didi

mysql - PostgreSQL 查询 : distinct count of jsonb values column

转载 作者:太空宇宙 更新时间:2023-11-03 10:30:49 27 4
gpt4 key购买 nike

我有一个名为 mainapp_project_data 的表,其中有一个 jsonb 列 project_user_data

  • 表格
 public | mainapp_project_data | table | admin

select project_user_data from mainapp_project_data;

                                         project_user_data

-----------------------------------------------------------------------------------------------------------------
[{"name": "john", "age": "21", "gender": "M"}, {"name": "randy", "age": "23", "gender": "M"}]
[{"name": "donald", "age": "31", "gender": "M"}, {"name": "wick", "age": "32",
"gender": "M"}]
[{"name": "orton", "age": "18", "gender": "M"}, {"name": "russel", "age": "55",
"gender": "M"}]
[{"name": "angelina", "age": "open", "gender": "F"}, {"name": "josep", "age": "21",
"gender": "M"}]
(4 rows)

(END)
  • 我想计算 JSON 的键 genderage 的不同值。

输出格式:[{key:count(repeated_values)}]

filtering on `gender` : [{"M":7},{"F":1}]
filtering on `age` : [{"21":2},{"23":1},{"31":1}.....]

最佳答案

WITH flat AS (
SELECT
kv.key,
-- make into a JSON object with a single value and count, e.g., '{"M": 7}'
jsonb_build_object(kv.value, COUNT(*)) AS val_count
FROM mainapp_project_data AS mpd
-- Flatten the JSON arrays into single objects per row
CROSS JOIN LATERAL jsonb_array_elements(mpd.project_user_data) AS unarrayed(udata)
-- Convert to a long, flat list of key-value pairs
CROSS JOIN LATERAL jsonb_each_text(unarrayed.udata) AS kv(key, value)
GROUP BY kv.key, kv.value
)
SELECT
-- de-deplicated object keys
flat.key,
-- aggregation of all values and counts per key
jsonb_agg(flat.val_count) AS value_counts
FROM flat
GROUP BY flat.key

返回

  key   |                                                  value_counts
--------+---------------------------------------------------------------------------------------------------------------------
gender | [{"M": 7}, {"F": 1}]
name | [{"josep": 1}, {"russel": 1}, {"orton": 1}, {"donald": 1}, {"wick": 1}, {"john": 1}, {"randy": 1}, {"angelina": 1}]
age | [{"18": 1}, {"32": 1}, {"21": 2}, {"23": 1}, {"open": 1}, {"31": 1}, {"55": 1}]

这将提供任何键值对实例计数。如果您只需要性别和年龄,只需在第一个 GROUP BY 子句之前添加一个 where 子句。

  WHERE kv.key IN ('gender', 'age')

关于mysql - PostgreSQL 查询 : distinct count of jsonb values column,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59399568/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com