postgres - 查询 jsonb 数组字段中的唯一值
postgres - querying for unique values in jsonb array field
我有一个 table 和一个 jsonb 列 'metadata'。在元数据列中有多个键值对,因此 table 的格式如下:
hash metadata
1 {"type": ["A, B"], "Name": ["One"]}
2 {"type": ["A, B, C"], "Name": ["Two"]}
3 {"type": ["B, C"], "Name": ["Three"]}
4 {"type": ["B"], "Name": ["Four"]}
我正在尝试查询 table 以获取包含每个唯一类型的元素的数量,例如:
type : count
"A" : 2
"B" : 4
"C" : 2
我查看了 Postgres 9.6 文档和许多其他堆栈溢出线程并尝试了一些东西,我能得到的最接近的是:
Select jsonb_array_elements(t.metadata -> 'Type') as type, count(DISTINCT t.hash)
FROM table AS t
GROUP BY type
哪个returns:
type : count
"A, B" : 1
"A, B, C" : 1
"B, C" : 1
"B" : 1
在 postgresql 中有什么方法可以做到这一点吗?
谢谢
您的元数据列格式不正确。现在它是一个包含 1 个项目的数组,它是一个字符串 ["A, B"]
而它应该是 ["A", "B"]
如果您无法修复列中的数据,可以在 select
中围绕您的类型添加更多函数调用
Select unnest(string_to_array(jsonb_array_elements(t.metadata -> 'Type'), ', ')) as type, count(DISTINCT t.hash)
FROM table AS t
GROUP BY type
我有一个 table 和一个 jsonb 列 'metadata'。在元数据列中有多个键值对,因此 table 的格式如下:
hash metadata
1 {"type": ["A, B"], "Name": ["One"]}
2 {"type": ["A, B, C"], "Name": ["Two"]}
3 {"type": ["B, C"], "Name": ["Three"]}
4 {"type": ["B"], "Name": ["Four"]}
我正在尝试查询 table 以获取包含每个唯一类型的元素的数量,例如:
type : count
"A" : 2
"B" : 4
"C" : 2
我查看了 Postgres 9.6 文档和许多其他堆栈溢出线程并尝试了一些东西,我能得到的最接近的是:
Select jsonb_array_elements(t.metadata -> 'Type') as type, count(DISTINCT t.hash)
FROM table AS t
GROUP BY type
哪个returns:
type : count
"A, B" : 1
"A, B, C" : 1
"B, C" : 1
"B" : 1
在 postgresql 中有什么方法可以做到这一点吗?
谢谢
您的元数据列格式不正确。现在它是一个包含 1 个项目的数组,它是一个字符串 ["A, B"]
而它应该是 ["A", "B"]
如果您无法修复列中的数据,可以在 select
中围绕您的类型添加更多函数调用Select unnest(string_to_array(jsonb_array_elements(t.metadata -> 'Type'), ', ')) as type, count(DISTINCT t.hash)
FROM table AS t
GROUP BY type