Re: Multiple Aggregations Order

From: Thomas Kellerer <spam_eater(at)gmx(dot)net>
To: pgsql-general(at)lists(dot)postgresql(dot)org
Subject: Re: Multiple Aggregations Order
Date: 2020-01-14 21:48:00
Message-ID: 1c30ad7f-fb8d-e407-8933-9de95dd305d2@gmx.net
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

João Haas schrieb am 14.01.2020 um 18:26:
> I'm working on a query where I need to fetch information from a table
> along with some data from a many-to-many connection table in a single
> query. My idea is to do an outer join with the connection query and
> aggregate the needed data in multiple 'array_agg's, and then handle
> this aggregated data later in code.
>
> The issue is, there are a lot of aggs (4 by now, may increase later),
> and I need to order these by a 'order' field on the connection table.
> I can put an 'ORDER BY "order"' statement inside each 'array_agg',
> but I don't think that would be the most efficient way. Doing the
> join with a sorted connection table didn't work for me as well,
> probably due to other joins on the query. I tried doing some stuff
> with subqueries, but all attempts ended up in either failure or
> increased query time.
>

What about aggregating into a single jsonb array?
You lose some of the data type information, but maybe that's OK for the backend that processes the data.

Something along the lines:

SELECT tb.*,
array_length(tree.tree_path, 1) AS depth,
jsonb_agg(jsonb_build_object('child_id', conn.child_id, 'kind', conn.kind, 'restrictions', conn.restrictions) order by conn."order")
FROM tb
...
GROUP BY ...

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Rene Romero Benavides 2020-01-14 22:08:32 Re: Postgresql Data corruption
Previous Message João Haas 2020-01-14 21:17:22 Re: Multiple Aggregations Order