From: Tom Lane <tgl@sss.pgh.pa.us>
To: Thorsten Glaser <tg@evolvis.org>
Cc: pgsql-general@lists.postgresql.org
Subject: Re: DISTINCT *and* ORDER BY in aggregate functions on expressions(!)
Date: Mon, 27 Feb 2023 20:32:58 -0500
Message-ID: <559416.1677547978@sss.pgh.pa.us> (raw)
In-Reply-To: <c02191c1-64a8-3350-6853-784bf5ce57@evolvis.org>
References: <23d08470-aaa8-afca-dfd7-37261487a1f8@evolvis.org>
<CAKFQuwZ1f0zmVsFpYeNL8c=waGSCJB5K4AmkqzdXXHXB3XX3Lw@mail.gmail.com>
<c02191c1-64a8-3350-6853-784bf5ce57@evolvis.org>
Thorsten Glaser <tg@evolvis.org> writes:
> On Mon, 27 Feb 2023, Tom Lane wrote:
>> Well, yeah. Simplify it to
>> SELECT array_agg(DISTINCT x ORDER BY y) FROM mytable;
> That’s… a bit too simple for this case.
Sure, I was just trying to explain the rule.
>> For the specific example you give, it's true that any specific
>> possible output of jsonb_build_object() would correspond to
>> a unique set of cot.weekday, cot.from_hour, cot.to_hour values.
> Not necessarily (see directly below), but why would that matter?
> It should sort the generated JSON objects within the array.
Well, that may be what you want, but it's not what you wrote in
the query. Follow David's advice and do
jsonb_agg(DISTINCT jsonb_build_object(
'weekday', cot.weekday,
'from_hour', cot.from_hour,
'to_hour', cot.to_hour)
ORDER BY jsonb_build_object(
'weekday', cot.weekday,
'from_hour', cot.from_hour,
'to_hour', cot.to_hour))
I'm pretty sure that this will only incur one evaluation of the
common subexpression, so even though it's tedious to type it's not
inefficient.
regards, tom lane
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: tgl@sss.pgh.pa.us, tg@evolvis.org
Subject: Re: DISTINCT *and* ORDER BY in aggregate functions on expressions(!)
In-Reply-To: <559416.1677547978@sss.pgh.pa.us>
References: <23d08470-aaa8-afca-dfd7-37261487a1f8@evolvis.org> <CAKFQuwZ1f0zmVsFpYeNL8c=waGSCJB5K4AmkqzdXXHXB3XX3Lw@mail.gmail.com> <c02191c1-64a8-3350-6853-784bf5ce57@evolvis.org> <559416.1677547978@sss.pgh.pa.us>
* 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