Postgres唯一的JSON阵列汇总值
我有一个存储这样的值的表:
| id | thing | values |
|----|-------|--------|
| 1 | a |[1, 2] |
| 2 | b |[2, 3] |
| 3 | a |[2, 3] |
并且想使用汇总函数thits
进行组,但仅存储数组的唯一值,以使结果是:
| thing | values |
|-------|---------|
| a |[1, 2, 3]|
| b |[2, 3] |
是否有一个简单的且表演者在Postgres中这样做的方式?
I have a table that stores values like this:
| id | thing | values |
|----|-------|--------|
| 1 | a |[1, 2] |
| 2 | b |[2, 3] |
| 3 | a |[2, 3] |
And would like to use an aggregate function to group by thing
but store only the unique values of the array such that the result would be:
| thing | values |
|-------|---------|
| a |[1, 2, 3]|
| b |[2, 3] |
Is there a simple and performant way of doing this in Postgres?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,您将JSON阵列与
JSON_ARRAY_ELEMENTS()
- 这是一个设置回收函数,带有JOIN HARISAL
您可以使用id
> ,thing
和每个元素的JSON数组元素。然后,您选择
不同的
记录thing
和value
,由value
订购。最后,您将记录与
json_agg()
一起汇总。在SQL中看起来像:
通常,您需要使用
JSONB
类型,因为这比json
更有效。然后,您必须使用相应的JSONB _...()
函数。First you take the JSON array apart with
json_array_elements()
- this is a set-returning function with aJOIN LATERAL
you get a row withid
,thing
and a JSON array element for each element.Then you select
DISTINCT
records forthing
andvalue
, ordered byvalue
.Finally you aggregate records back together with
json_agg()
.In SQL that looks like:
In general you would want to use the
jsonb
type as that is more efficient thanjson
. Then you'd have to use the correspondingjsonb_...()
functions.