简体   繁体   English

postgres-在jsonb数组字段中查询唯一值

[英]postgres - querying for unique values in jsonb array field

I have a table with a jsonb column 'metadata'. 我有一个带有jsonb列“元数据”的表。 In the metadata column there are multiple key-value pairs so the table is formatted as such: 在元数据列中有多个键值对,因此表的格式如下:

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"]}

I am trying to query the table so as to get the number of elements that contain each unique type, as such: 我试图查询表以便获取包含每个唯一类型的元素的数量,例如:

type  :  count
"A"   :   2
"B"   :   4
"C"   :   2

I have looked through the Postgres 9.6 documentation and many of the other stack overflow threads and tried a couple of things and the closest I can get is with this: 我浏览了Postgres 9.6文档和许多其他堆栈溢出线程,并尝试了几件事,而我能找到的最接近的是:

Select jsonb_array_elements(t.metadata -> 'Type') as type, count(DISTINCT t.hash)
FROM table AS t
GROUP BY type

which returns: 返回:

 type     :  count
"A, B"    :   1
"A, B, C" :   1
"B, C"    :   1
"B"       :   1

Is there any way to do this in postgresql? 有什么办法可以在PostgreSQL中做到这一点?

Thanks 谢谢

Your metadata column is malformed. 您的元数据列格式错误。 Right now it is an array of 1 item that is a string ["A, B"] when it should be ["A", "B"] 现在,它是由1个项目组成的数组,当它应为["A", "B"]时为字符串["A, B"] ["A", "B"]

If you can't fix the data in the column, you can add a few more function calls around your type in the 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM