Postgres唯一的JSON阵列汇总值

发布于 2025-01-26 03:05:41 字数 365 浏览 5 评论 0原文

我有一个存储这样的值的表:

| 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

狼亦尘 2025-02-02 03:05:41

首先,您将JSON阵列与JSON_ARRAY_ELEMENTS() - 这是一个设置回收函数,带有JOIN HARISAL您可以使用id> ,thing和每个元素的JSON数组元素。

然后,您选择不同的记录thingvalue,由value订购。

最后,您将记录与json_agg()一起汇总。

在SQL中看起来像:

SELECT thing, json_agg(value) AS values
FROM (
    SELECT DISTINCT thing, value
    FROM t
    JOIN LATERAL json_array_elements(t.values) AS v(value) ON true
    ORDER BY value) x
GROUP BY thing

通常,您需要使用JSONB类型,因为这比json更有效。然后,您必须使用相应的JSONB _...()函数。

First you take the JSON array apart with json_array_elements() - this is a set-returning function with a JOIN LATERAL you get a row with id, thing and a JSON array element for each element.

Then you select DISTINCT records for thing and value, ordered by value.

Finally you aggregate records back together with json_agg().

In SQL that looks like:

SELECT thing, json_agg(value) AS values
FROM (
    SELECT DISTINCT thing, value
    FROM t
    JOIN LATERAL json_array_elements(t.values) AS v(value) ON true
    ORDER BY value) x
GROUP BY thing

In general you would want to use the jsonb type as that is more efficient than json. Then you'd have to use the corresponding jsonb_...() functions.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文