From: Thomas Kellerer <spam_eater@gmx.net>
To: pgsql-general@lists.postgresql.org
Subject: Re: Multiple Aggregations Order
Date: Tue, 14 Jan 2020 22:48:00 +0100
Message-ID: <1c30ad7f-fb8d-e407-8933-9de95dd305d2@gmx.net> (raw)
In-Reply-To: <CAEi5ktJxKt5OYbVS7Xzzas3o=BmKfGGd3_wsXT0OVZPr==yoog@mail.gmail.com>
References: <CAEi5ktJxKt5OYbVS7Xzzas3o=BmKfGGd3_wsXT0OVZPr==yoog@mail.gmail.com>
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 ...
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Reply to all the recipients from your mail client; the link fills in
the headers below: reply via email
Some clients, webmail especially, drop In-Reply-To and References from
a link, and the reply then starts a new thread: use the mbox below.
To: pgsql-general@postgresql.org
Cc: spam_eater@gmx.net
Subject: Re: Multiple Aggregations Order
In-Reply-To: <1c30ad7f-fb8d-e407-8933-9de95dd305d2@gmx.net>
References: <CAEi5ktJxKt5OYbVS7Xzzas3o=BmKfGGd3_wsXT0OVZPr==yoog@mail.gmail.com> <1c30ad7f-fb8d-e407-8933-9de95dd305d2@gmx.net>
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox